I've got a few select lists on my form which look a bit like this:
<option value="400000" <?php if($_GET['MaxPrice'] == "400000") { echo("selected"); } ?>>£400,000</option>
As you can see (above) I've got a bit of PHP in there telling the form to remember it's selection upon submit.
Is there a short bit of PHP that would remember every selection without the rather heavy method I'm using above?
UPDATE:
<select name="MaxPrice" id="MaxPrice">
<option value="9999999" selected>Price (Max)</option>
<option value="100000" <?php if($_GET['MaxPrice'] == "100000") { echo("selected"); } ?>>£100,000</option>
<option value="200000" <?php if($_GET['MaxPrice'] == "200000") { echo("selected"); } ?>>£200,000</option>
<option value="300000" <?php if($_GET['MaxPrice'] == "300000") { echo("selected"); } ?>>£300,000</option>
<option value="400000" <?php if($_GET['MaxPrice'] == "400000") { echo("selected"); } ?>>£400,000</option>
</select>
UPDATE 2: Is there a way to implement this technique into some JavaScript?
if (BuyRent=='buy')
document.SearchForm.MaxPrice.options[9999999]=new Option("Price (Max)","150000000");
document.SearchForm.MaxPrice.options[100000]=new Option("\u00A3100,000","100000");
document.SearchForm.MaxPrice.options[200000]=new Option("\u00A3200,000","200000");
document.SearchForm.MaxPrice.options[300000]=new Option("\u00A3300,000","300000");
document.SearchForm.MaxPrice.options[400000]=new Option("\u00A3400,000","400000");
Usually, you use some kind of loop. Here's an example :
$my_values = array(100000, 200000, 300000, 400000);
foreach($my_values as $value) {
echo "<option value=\"{$value}\"";
echo ($_GET['MaxPrice'] == $value) ? 'selected="selected"';
echo ">" . number_format($value, 0, '.', ',') . "</option>";
}
Which would print 4 tags such as <option value="100000" selected="selected">100,000</option>.
This code also uses the ternary operator, but it's obviously not mandatory, you can write the whole if/else statement if wanted.
Edit:
<select name="MaxPrice" id="MaxPrice">
<option value="9999999">Price (Max)</option>
<?php
$my_values = array(100000, 200000, 300000, 400000);
foreach($my_values as $value) {
echo "<option value=\"{$value}\"";
echo ($_GET['MaxPrice'] == $value) ? 'selected="selected"' : "";
echo ">£ " . number_format($value, 0, '.', ',') . "</option>";
}
?>
</select>
good question, it made me wonder if there exists a js plugin to remember form field out there.
And the answer seems to be "Yes!"
Related
Wondering if you can show me a better way to handle this logic? I wrote this and am very ashamed of it. Can you show me a better optimized version of this logic?
P.S $result["item"]; returns an integer.
$type = $result["item"];
switch ($type){
case "1":
$type_output = '
<option value="1" selected>Cash</option>
<option value="2">Cheque</option>
<option value="3">Debit Card</option>
<option value="4">Credit Card</option>';
break;
case "2":
$type_output = '
<option value="1">Cash</option>
<option value="2" selected>Cheque</option>
<option value="3">Debit Card</option>
<option value="4">Credit Card</option>';
break;
case "3":
$type_output = '
<option value="1">Cash</option>
<option value="2">Cheque</option>
<option value="3" selected>Debit Card</option>
<option value="4">Credit Card</option>';
break;
case "4":
$type_output = '
<option value="1">Cash</option>
<option value="2">Cheque</option>
<option value="3">Debit Card</option>
<option value="4" selected>Credit Card</option>';
break;
}
html
<td>
<select style="width:200px;" name="payment_type">
<option value=""> </option>
'.$type_output.'
</select>
</td>
Thank you
I would use this approach
$type = $result["item"];
$type_output = "";
$options =array(
"1"=>"cash",
"2"=>"Cheque",
"3"=>"Debit Card",
"4"=>"Credit Card",
);
foreach($options as $value=>$text) {
$type_output .= "<option value=\"$value\"".($type==$value? " selected" : "").">$text</option>\n";
}
you could do it this way and only once
<option value="1" <?php if ($type == 1) echo "selected"; ?>>Cash</option>
<option value="2" <?php if ($type == 2) echo "selected"; ?>>Cheque</option>
<option value="3" <?php if ($type == 3) echo "selected"; ?>>Debit Card</option>
<option value="4" <?php if ($type == 4) echo "selected"; ?>>Credit Card</option>
You're repeating a lot of stuff here. You can do something like
<option value="..." <?php if($type == 1) { print "selected"; } ?> >Something</option>
This would work, however you're probably better off using a template engine and letting it handle this sort of stuff for you.
http://www.smarty.net/docsv2/en/language.function.html.options.tpl
Try this
type_output = '
<option value="1"'.($type == 1 ? " selected" : "").'>Cash</option>
<option value="2"'.($type == 2 ? " selected" : "").'>Cheque</option>
<option value="3"'.($type == 3 ? " selected" : "").'>Debit Card</option>
<option value="4"'.($type == 4 ? " selected" : "").'>Credit Card</option>';
Try this in your document:
<option value="1" <?php if ($type == 1) echo 'selected="selected"' ?>>Cash</option>
<option value="2" <?php if ($type == 2) echo 'selected="selected"' ?>>Cheque</option>
<option value="3" <?php if ($type == 3) echo 'selected="selected"' ?>>Debit Card</option>
<option value="4" <?php if ($type == 4) echo 'selected="selected"' ?>>Credit Card</option>'
Bear in mind that selected on its own is invalid, at least in XHTML. You might get away with it in HTML5, but personally I'd do it properly, as above. Either way, make sure you check your HTML output against the W3C validator.
Also, I tend not to wrap large blocks of HTML in PHP strings, as you have done; it is better to use HTML mode and break into PHP where dynamic output is required. This allows your IDE to understand the structure of your document, and allows syntax colouration and auto-complete to work.
Ashamed)))
sel = document.getElementById("select_id");
if($type>=0&&$type<sel.options.length)
sel.options[$type].selected=true;
do it onLoad or better onDomReady... or just after you options code. Don't forget to assign an id:
<select id="select_id">...
if you're controlling an input, then it would be JUST ONE LINE of JS:
document.getElementById("select_id").options[$type].selected=true;
You could use a function like this:
function selected($selected, $current) {
if($selected == $current)
return "selected";
}
And then:
$options = array(
1 => 'Cash',
2 => 'Cheque',
3 => 'Debit Card',
4 => 'Credit Card'
);
foreach($options as $value => $option)
echo '<option value="'.$value.'" '.selected($value, $type).'>'.$option.'</option>';
Note that the selected function is applicable in other similar cases too.
Here's how I'd do it.
$options = array(
"1"=>"Cash",
"2"=>"Cheque",
"3"=>"Debit Card",
"4"=>"Credit Card"
);
$type = $result['item'];
$type_output = "";
foreach($options as $value=>$text) {
if($value==$type){
$selected = " selected";
}
else {
$selected = "";
}
$type_output .= '<option value="'.$value.'"'.$selected.'>'.$text.'</option>';
}
Just noticed Chumkiu had a similar answer, but I'll post mine anyway in case this is clearer to some folk than the ternary if statement
I have a number field and a drop-down list that I am using as part of a form, as follows:
<label for="height">Height/Thickness</label>:
<input <?php if (empty($messages) == false) {echo 'value="'.htmlentities($_POST['height'], ENT_QUOTES).'"';} ?> type="number" name="height" id="height" />
<select class="dimensions" name="heightunit">
<option value="">Select...</option>
<option value="mm">mm</option>
<option value="cm">cm</option>
<option value="m">m</option>
<option value="in">in</option>
</select>
The $messages variable is an array that stores any error messages generated by the form. The bit between the <?php & ?> tags are there to ensure that if there is an error, that it will echo back the values the user entered before they submitted, so saving them time (and frustration) from entering the data again.
I want to do the same with the drop down list. At the moment, I am adding the following line within each option tag (similar to this answer):
<?php if ((empty($messages) == false) && ($_POST['lengthunit'] == 'mm') {echo 'selected="selected"';} ?>
But then it's really untidy:
....
<select class="dimensions" name="lengthunit">
<option value="" <?php if ((empty($messages) == false) && ($_POST['lengthunit'] == '') {echo 'selected="selected"';} ?>>Select...</option>
<option value="mm" <?php if ((empty($messages) == false) && ($_POST['lengthunit'] == 'mm') {echo 'selected="selected"';} ?>>mm</option>
<option value="cm" <?php if ((empty($messages) == false) && ($_POST['lengthunit'] == 'cm') {echo 'selected="selected"';} ?>>cm</option>
<option value="m" <?php if ((empty($messages) == false) && ($_POST['lengthunit'] == 'm') {echo 'selected="selected"';} ?>>m</option>
<option value="in" <?php if ((empty($messages) == false) && ($_POST['lengthunit'] == 'in') {echo 'selected="selected"';} ?>>in</option>
</select>
My question is - Is there a more elegant way to do this, without adding the php tag inside each option tag?
(I am thinking along the lines of:
if (OPTION_VALUE === $_POST['heightunit']) {echo 'selected="selected"';}. Is there anything that can be substituted for the OPTION_VALUE?)
EDIT: The reason I want to do this is because I want to apply this to a list of countries, which is over 200, and I just want to write 'good code'.
**EDIT: Looking back at it now, it looks so easy...anyways, thank you for your help and this is what I went with in the end:
function lengthlist($selectname) {
$distanceunits = array('','mm','cm','m','in');
foreach ($distanceunits as $value) {
if ($value == '') {$value = '...';}
if ($value == $_POST["$selectname"]) {
echo "<option value=\"$value\" selected=\"selected\">$value</option>";
} else {
echo "<option value=\"$value\">$value</option>";
}
}
}
Or you can also load the dimensions values in an array and then just write them on a while loop
<select class="dimensions" name="lengthunit">
<option>Select...</option>
<?php
$i=0;
$array=array("mm", "cm", "m", "in");
while ($i<4){ ?>
<option value="<?php echo $array[$i];?>"<?php if ((empty($messages) == false) &&
($_POST['lengthunit'] == $array[$i])) {echo 'selected="selected"';} ?>><?php echo
$array[$i];?></option>
<?php $i++; } ?>
</select>
Because in other cases you might wish to add more options for the users to select, so you would just add them to the array. You can also use a foreach loop instead of a while
if you want more elegant way - do it opposite way - move php outside of the option tag.
You can generate the whole list together with the tags from within php, like:
<?
/*some loop*/
echo "<option value='a' {$selected} >aaa</option>";
/*end of the loop*/
?>
where $selected is previously set as "selected" or just empty string. And use arrays of course as appropriate.
i would like to give a dropdown a default value with php / mysql queries
like in the db table users there is a record saying usergroup
and i want it so the dropdown default value changes to the value of that record i got this code so far:
Usergroup: <select value=\"" . $usergroup . "\" name='usergroup'>
<option value='4'>Administrator</option>
<option value='3'>Moderator</option>
<option value='2'>Donator</option>
<option value='1'>Regular Member</option>
</select>
and php part:
$username = mysql_real_escape_string(htmlentities(stripslashes($_POST['username'])));
$query="SELECT * FROM users where `username` like '{$username}'";
$result = mysql_query($query);
$num = mysql_numrows($result);
$i=0;
while ($i < $num) {
$username2=mysql_result($result,$i,"username");
$name=mysql_result($result,$i,"name");
$usergroup=mysql_result($result,$i,"usergroup");
$email=mysql_result($result,$i,"email");
$ip=mysql_result($result,$i,"ip");
$profpic=mysql_result($result,$i,"profilepic");
$id=mysql_result($result,$i,"id");
$i++;
}
thanks in regards!
i gotten it to work with a few if statements, i was planning to use it that way but didn't want the code to become too messy:
if ($usergroup == 4) {
echo "<select name='usergroup'><option value='4' selected='selected'>Administrator</option><option value='3'>Moderator</option><option value='2'>Donator</option><option value='1'>Regulat Member</option></select><br>";
}
if ($usergroup == 3) {
echo "<select name='usergroup'><option value='4'>Administrator</option><option value='3' selected='selected'>Moderator</option><option value='2'>Donator</option><option value='1'>Regulat Member</option></select><br>";
}
if ($usergroup == 2) {
echo "<select name='usergroup'><option value='4'>Administrator</option><option value='3'>Moderator</option><option value='2' selected='selected'>Donator</option><option value='1'>Regulat Member</option></select><br>";
}
if ($usergroup == 1) {
echo "<select name='usergroup'><option value='4'>Administrator</option><option value='3'>Moderator</option><option value='2'>Donator</option><option value='1' selected='selected'>Regulat Member</option></select><br>";
}
This is probably what you are looking for:
<?php
// $userGroup = the value from the database
$userGroup = 4;
?>
<select>
<option <?php echo ($userGroup) == 1 ? "selected" : "" ?> value="1">Administrator</option>
<option <?php echo ($userGroup) == 2 ? "selected" : "" ?> value="2">Moderator</option>
<option <?php echo ($userGroup) == 3 ? "selected" : "" ?> value="3">Donator</option>
<option <?php echo ($userGroup) == 4 ? "selected" : "" ?> value="4">Regular member</option>
</select>
If you don't recognize the if/else syntax (shorthand), check out this guide. Really handy for situations like this.
I'm dealing with a registration form at the moment, specifically, I'm dealing with redisplaying any information the user enters into the inputs if there is an error in the registration verification.
Normally, when a user hits 'submit' - if there is an error, the page refreshes and they are echoed out and the form is redisplayed. The problem is there is sometimes genuinely valid information in some of the fields, and by regrabbing that data, it can be redisplayed using the value attribute and the isset() function like so (if of course that data has been POSTed, which in this case it has):
<input type="email" name="anEmail"
value=" <?php echo (isset($email)) ? $email : false; ?>" />
That works fine for the <input> element, but is the same achievable with a dropdown list through the <select> element?
I initially tried:
<select name="region"
value="<?php echo (isset($region)) ? $region : 'Auckland'; ?>" >
<!-- with 'Auckland' being the default value of the list -->
However, it doesn't seem like that value="" is a valid attribute for the <select> tag.
Any ideas on how I could accomplish this? Cheers.
function build_select($name, array $options = NULL, $selected = NULL)
{
foreach($options as $value => $option)
$return .= ($value != $selected)? '<option value="'.$value.'">'.$option.'</option>': '<option selected="selected" value="'.$value.'">'.$option.'</option>';
return '<select name="'.$name.'">'.$return.'</select>';
}
echo build_select('region', array('Lorem' => 'Ipsum', 'Auckland' => 'Auckland', 'Ipsum' => 'Lorem'), 'Auckland');
HTML
<select name="region">
<option value="Lorem">Ipsum</option>
<option selected="selected" value="Auckland">Auckland</option>
<option value="Ipsum">Lorem</option>
</select>
You have to add selected="selected" to specific option. Like so:
<select name="region">
<option value="opt1">Option 1</option>
<option value="opt2" selected="selected">Option 2</option>
<option value="opt3">Option 3</option>
<option value="opt4">Option 4</option>
</select>
With this code Option 2 is selected
And in pehe you have to check if specific option equals the input.
<option value="opt4"<?php if ($region == "opt2"){ echo ' selected="selected"'; } ?>>Option 4</option>
it's selected="selected", i think. or just "selected".
a quick example of how you might implement that:
case "value0":
$selected0 = "selected";
break;
case "value1":
$selected1 = "selected";
break;
<option value="value0" <?php echo $selected0;?>></option>
<option value="value1" <?php echo $selected1;?>></option>
function __selected($ctrlName,$value)
{
if(isset($_REQUEST[$ctrlName]) && trim($_REQUEST[$ctrlName]) == trim($value))
return "selected='selected'";
else
return false;
}
use like
<select name="cmbCondition">
<option value="Excellent" <?php echo __selected('cmbCondition',"Excellent")?>>Excellent</option>
<option value="Good" <?php echo __selected('cmbCondition',"Good")?>>Good</option>
<option value="Poor" <?php echo __selected('cmbCondition',"Poor")?>>Poor</option>
</select>
One way you can do this if number of options are not much:
In every option put the code:
<select>
<option selected="<?php echo (isset($region) && $region=='Volvo') ? $region : ''; ?>">Volvo</option>
<option selected="<?php echo (isset($region) && $region=='Saab') ? $region : ''; ?>">Saab</option>
<option selected="<?php echo (isset($region) && $region=='Mercedes') ? $region : ''; ?>">Mercedes</option>
<option selected="<?php echo (isset($region) && $region=='Audi') ? $region : ''; ?>">Audi</option>
</select>
But if options are much in number javascript code is needed to be written..
if(isset($region))
{
echo '
<script>$("#id option").each(function()
{
if($(this).val()=='.$region.')
$(this).attr("selected", "selected");
});
</script>';
}
Dynamiclly creating options basod on array.
Usage should be pretty straightforward.
<?php
function rennder_options($options = array(), $selection = null) {
if (!is_array($options)) {
return false;
}
$result = "";
foreach($option as $option) {
$option_str = '<option value="'.$option['value'].'"';
if ($selection !== null && $option['value'] == $selection){
$option_str .= ' selected="selected"';
}
$option_str .= '>'.$option['name'].'</option>';
$result .= $option_str;
}
return result;
}
$options = array(
array( "value" => "opt1", "name" => "Option 1" )
array( "value" => "opt2", "name" => "Option 2" ),
array( "value" => "opt3", "name" => "Option 3" ),
);
?>
<select name="region">
<?php echo render_options($options, $_POST['region']); ?>
</select>
I currently have a form built in which after validation, if errors exist, the data stays on screen for the consumer to correct. An example of how this works for say the 'Year of Birth' is:
<select name="DOB3">
<option value="">Year</option>
<?php
for ($i=date('Y'); $i>=1900; $i--)
{
echo "<option value='$i'";
if ($fields["DOB3"] == $i)
echo " selected";
echo ">$i</option>";
}
?>
</select>
If an error is found, the year of birth value returns the year previously entered. I am able to have this work on all field with the exception of my 'State' field. I build the array and function for the drop down with the following code:
<?php
$states_arr = array('AL'=>"Alabama",'AK'=>"Alaska",'AZ'=>"Arizona",'AR'=>"Arkansas",'CA'=>"California",'CO'=>"Colorado",'CT'=>"Connecticut",'DE'=>"Delaware",'DC'=>"District Of Columbia",'FL'=>"Florida",'GA'=>"Georgia",'HI'=>"Hawaii",'ID'=>"Idaho",'IL'=>"Illinois", 'IN'=>"Indiana", 'IA'=>"Iowa", 'KS'=>"Kansas",'KY'=>"Kentucky",'LA'=>"Louisiana",'ME'=>"Maine",'MD'=>"Maryland", 'MA'=>"Massachusetts",'MI'=>"Michigan",'MN'=>"Minnesota",'MS'=>"Mississippi",'MO'=>"Missouri",'MT'=>"Montana",'NE'=>"Nebraska",'NV'=>"Nevada",'NH'=>"New Hampshire",'NJ'=>"New Jersey",'NM'=>"New Mexico",'NY'=>"New York",'NC'=>"North Carolina",'ND'=>"North Dakota",'OH'=>"Ohio",'OK'=>"Oklahoma", 'OR'=>"Oregon",'PA'=>"Pennsylvania",'RI'=>"Rhode Island",'SC'=>"South Carolina",'SD'=>"South Dakota",'TN'=>"Tennessee",'TX'=>"Texas",'UT'=>"Utah",'VT'=>"Vermont",'VA'=>"Virginia",'WA'=>"Washington",'WV'=>"West Virginia",'WI'=>"Wisconsin",'WY'=>"Wyoming");
function showOptionsDrop($array, $active, $echo=true){
$string = '';
foreach($array as $k => $v){
$s = ($active == $k)? ' selected="selected"' : '';
$string .= '<option value="'.$k.'"'.$s.'>'.$v.'</option>'."\n";
}
if($echo) { echo $string;}
else { return $string;}
}
?>
I then call the function from within the form using:
<td><select name="State"><option value="">Choose a State</option><?php showOptionsDrop($states_arr, null, true); ?></select></td>
Not sure what I'm missing but would love any assistance if somebody sees the error in my code.
Thanks!
Have a look at the code:
<?php showOptionsDrop($states_arr, null, true); ?>
You are passing null, so $active will always be null. The condition
($active == $k)
will never we evaluate to true.
You should pass the value you get from the form instead, e.g.:
<?php showOptionsDrop($states_arr, isset($fields['State']) ? $fields['State'] : null, true); ?>
You really should try to separate the PHP from the HTML, especially in your first example
Update:
Actually it is not that much, but consider to use the alternative syntax for control structures:
<select name="DOB3">
<optgroup label="Year">
<?php for ($i=date('Y'); $i>=1900; $i--) : ?>
<option value="<?php echo $i ?>"
<?php echo ($fields["DOB3"] == $i) ? 'selected="selected"' : '' ?> >
<?php echo $i ?>
</option>
<?php endforeach; ?>
</optgroup>
</select>
Also if you want to give the options some kind of label, you can do this with the optgroup HTML tag (this is not selectable).