Make an option selected based on $_GET. Is this even possible? - php

I have a quick question.
Is it possible to do something like this?
The options are generated dynamically based on foreach loop. I want the loop to stop where the $_GET['t'] equals the $k and make it selected.
<option value="http://domain.com/<?php print $k; ?>/" <?php if ($k == $_GET['t']) print 'selected'; ?>><?php print $v; ?></option>
Basically is there a way to make the option selected/highlighted based on the provided $_GET[t'] value on the address bar.. I tried it and i get undefined index: t error.
am i missing something?
Thanks a lot.

You get the undefined error because "t" is not in your $_GET request.
make sure you are calling the right url (i.e.: example.com/script.php?t=test)
Do make sure you are checking for the value (as others suggested) with isset($_GET['t'])

You almost got it - the xhtml is actually selected="selected"
<option value="http://domain.com/<?php print $k; ?>/" <?php if ($k == $_GET['t']) print 'selected="selected"'; ?>><?php print $v; ?></option>

Above what adam noted, are you testing by actually passing a "t=something" on the end? This code should get rid of the error by testing to see if t was set first:
<option value="http://domain.com/<?php print $k; ?>/" <?php if (isset($_GET['t']) && $k == $_GET['t']) print 'selected="selected"'; ?>><?php print $v; ?></option>

You shouldn't use GET's to change form values on a page. You should use POST for that :)
This way, if anyone crawls your page, they won't have 10 times the same page with just the select box changed :)

Related

issue with IF statement returning unexpected result

I am trying to achieve the following...
Each 'element' should have the option to choose one 'sibling' from a select dropdown, the siblings are chosen from all of the other elements, the sibling cannot be itself, but a sibling doesn't have to be assigned. If one is assigned it should be selected by default in the select list.
<?php echo $sibling; ?>
<select name="sibling">
<option value="none">none</option>
<?php
while($row = $result->fetch_array()) {
if($row['element']!=$element){
echo '<option value="'.$row['element'].'" ';
if($row['sibling']==$sibling){
echo 'selected="selected"';
}
echo '>'.$row['element'].'</option>';
}
}
?>
</select>
I have almost achieved what I want but for some reason the code doesn't add selected="selected" to the right option.
I'd appreciate any guidance anyone could give in where I may be going wrong? I'm fairly new to PHP so I may be going about this in the wrong way.
$element and $sibling are equal to $row['element'] and $row['sibling'] for the corresponding $id which is an index that is passed to the page on a query string.
UPDATE: FOUND ANSWER
So with a little investigation this was glaringly obvious.
The line containing...
if($row['sibling']==$sibling)
should have been...
if($row['element']==$sibling){
Thanks to #RyanS for suggesting the var dump.

getting default value of dropdown box html in php loop

So I have this problem, which I don't see how it's happening. Basically I have 2 arrays one of which has a list of apparatus and the other just has one apparatus that the user can operate. I want to have a dropdown list of all the apparatus avliable, but the default value that is selected is the one that they can operate (They can only operate one at a time) Here is the code, and I have an if statement to check if the user can operate it and selected = "selected" but that doesn't seem to be working (In firefox)... Any help would be great.
Thanks!
<?php
foreach ($apparatuslist as $apparatus):?>
<option value="<?php echo $apparatus['apparatus'];?>" <?php if ($driveron['apparatus'] == $apparatus['apparatus']){echo "SELECTED";} ?> ><?php echo substr($apparatus['apparatus'], 5); ?></option>
<?php endforeach;?>
You have it right in your question, but not in your code
<?php
foreach ($apparatuslist as $apparatus):?>
<option value="<?php echo $apparatus['apparatus'];?>" <?php if ($driveron['apparatus'] == $apparatus['apparatus']){echo "selected=\"selected\"";} ?> ><?php echo substr($apparatus['apparatus'], 5); ?></option>
<?php endforeach;?>
Should do the trick..
The code is correct. It's optional whether you write select="selected" or jus "selected" that doesn't effect firefox.The code is correct but not working means the problem in browser i guess. Either it is cache problem as newer version of firefox has cache problem or there may be other kind of problem in firefox. Please check in other computer's firefox.
correct syntax is: selected="selected" in OPTION tag

how to keep the choosed data in the <select> element? HTML

here I have stupid question, hope you can help me.
I create a menu using Select element and option like this:
<option selected="selected">Select type...</option>
<option value="1">Doctor</option>
<option value="2">Patient</option>
and every time I need to pick one value from this menu and use the submit button next to it to transfer data.
But every time the page refreshed, this menu will reveal: Select type...
I want it to reveal the value I chose last time, but don't know how.
Many thanks in advance!!
You'll want to move that selected="selected" onto the selected option.
Doing so in PHP isn't too rough. Just check the $_POST or $_GET (however you sent the form) value for your select box, such as $_POST["selectBox"] for each value down the list. When you find a match, echo out the selected="selected" string there. If the value was empty, output it on your default value.
The easiest way to achieve this is to populate the <select> options in an array, then loop through it to display the <option> list and mark them as selected is the $_POST variable matches the correct value:
<?php $myselect = array(1=>'Doctor', 2=>'Patient'); ?>
<select name="myselect">
<option>Select type...</option>
<?php foreach ($myselect as $value => $label): ?>
<option value="<?php echo $value; ?>"<?php if (isset($_POST['myselect']) && $_POST['myselect'] == $value) echo ' selected'; ?>>
<?php echo $label; ?>
</option>
<?php endforeach; ?>
</select>
<select name="myselect">
<?php
$myselect = array('Select type...','Doctor','Patient');
for($i=0; $i<=2; $i++){
echo "<option value=\"{myselect[$i]}\"";
if (isset($_POST['myselect']) && $_POST['myselect'] == $myselect[$i]){
echo 'selected=\"selected\"';
}
echo ">{$myselect[$i]}</option>";
}
?>
</select>
You have to use the server-side language of you choice to store the selected value in a database, xml or text file.
Edit : I think I may have misunderstood your question.
There are a few ways to do this.
On submit you can save that value as a $_SESSION value and use that to set the select on page load.
Using Javascript you can either set a cookie on change or alter the url to add a parameter (url?selecttype=1) and set that on page load using PHP.
There's a good use of cookies in JS on quirksmode: http://www.quirksmode.org/js/cookies.html
You need to change which one is selected to match the request....
function create_select($properties, $opts)
{
$out="<select ";
foreach ($properties as $propname=>$propval) {
$out.=" $propname='$propval'";
}
$out.=">\n";
foreach ($opts as $val=>$caption) {
$out.="<option value='$value'";
if ($_REQUEST[$properties['name']]==$val) $out.=" SELECTED";
$out.=">$caption</option>\n";
}
$out.="</select>";
return $out;
}
print create_select(array('name'=>'direction',
'id'=>'direction',
'class'=>'colourful',
'onChange'=>''),
array('N'=>'North',
'S'=>'South',
'E'=>'East',
'W'=>'West'));

How can I add text into a certain area?

If I have a line like this,
<option value="someval">somval</option>
how can I position the cursor after the last quotation of value and put something like abcdef?
So the output would be
<option value="somval" abcdef>somval</option>
with PHP?
I want to do this dynamically and I can't figure out how to do it. I'm looking at strpos(), but I don't see how it can be done. I'll be posting a bunch of option tags into a textbox and code will be generated. so I'll have a lot of option fields.
#martin - Say I have a huge dropdown and each option lists a country that exists. Rather than having to manually type out something like this:
$query = $db->query("my query....");
while($row = $db->fetch($query)) {
<select name="thename">
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
... Followed by 100 more, because there are a lot of locations to list.
</select>
How can I post all the options I have into a textbox and have the above code automatically generated to save a lot of time?
Using your example you would do:
while($row = $db->fetch($query)) {
printf('<option value="someval"%s>someval</option>',
($row['someval'] == 'someval') ? ' selected="selected" ' : '');
}
This would go through the rows and output an option, replacing the %s with the attribute selected="selected" if $row['someval'] is equal to someval. However, the above is rather pointless, because all option elements will have the same value and text, so try
while($row = $db->fetch($query)) {
printf('<option value="%s"%s>%s</option>',
$row['country-code'],
($row['country-code'] === $selection) ? ' selected="selected" ' : '',
row['country-name']);
}
With $selection being anything you want to compare against. Replace the keys in $row with appropriate keys from in your database.
Note: The usual disclaimers about securing your output apply
You could capture (value=".+?") and replace it with $0 abcdef.
<?php
$string = '<option value="someval">someval</option>';
print preg_replace("/(value=\".+?\")/i", "$0 abcdef", $string);
?>
Which outputs the following:
<option value="someval" abcdef>someval</option>
With PHP, you can generate a whole string with any text you wish. Where do you have your original string? In a variable or a text file?

Validating html with php

Something is wrong with my print "<option value...";
line of php code.
It keeps generating error messages:
an attribute value specification must be an attribute value literal unless SHORTTAG YES is specified
<option value = Addition>Addition</option>
<and so on...>
Okay, so how do i fix this line of code:
//foreach loop to cycle through the array
foreach ($testFiles as $myFile)
{
$fileBase = substr($myFile, 0, strlen($myFile) - 5);
**//Problem here:**
print "<option value = $fileBase>$fileBase</option>\n";
} // end foreach
such that's it's html compliant, the php code works fine, I just need validation on the html, cause you can't validate php, and the variable $fileBase references an html file, in this case Addition would be one of the files allotted to $fileBase.
print "<option value = \"$fileBase\">$fileBase</option>\n";
Should do it
print "<option value='$fileBase'>$fileBase</option>\n";
There are a few other options:
You could use printf:
printf('<option value="%s">%s</option>', $fileBase, $fileBase);
A here-doc:
echo <<<HTML
<option value="$fileBase">$fileBase</option>
HTML;
You could drop out of PHP temporarily (generally a good technique, but not very pretty here):
<?
foreach ($testFiles as $myFile) {
$fileBase = substr($myFile, 0, strlen($myFile) - 5);
?>
<option value="<?= htmlentities($fileBase) ?>"><?= htmlentities($fileBase) ?></option>
<?
}
?>
But really, what you should be doing is using one of the many templating systems out there, and not mixing HTML in with your code.

Categories