HTML selecting last selected dropdown value? - php

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>

Related

Pre Select an Option in a form based on variable?

<select name="radio_typ" id="radio_typ" >
<option value="P5100">P5100</option>
<option value="P5400">P5400</option>
<option value="P7100">P7100</option>
<option value="P7200">P7200</option>
<option value="700P">Jaguar 700p</option>
<option value="LPE200">LPE200</option>
<option value="XL200">XL200</option>
</select>
I'd like to be able to pre-select an option in a drop down menu based on a variable from a database which will already be set to the current setting. This form is for the purpose of editing the setting if needbe.
I tried inserting value="<?php echo $radio_typ;?> but that didn't seem to work.
Any hints as to how I could do this?
Thank you twofed.
That code didn't quite work, but I was able to figure out a solution that did based on that thought process.
<select name="radio_typ" id="radio_typ" >
<?php foreach ($options as $value => $name) {
if ($value == $radio_typ) {
$sel = "selected";
} else {
$sel = "";
}?>
<option value="<?= $value; ?>" <?= $sel; ?>><?= $name; ?></option>
<?php } ?>
</select>
I think, the best solution would be:
<?php
$radio_typ = "700P";
// value => name
$options = [
"P5100" => "P5100",
"P5400" => "P5400",
"P7100" => "P7100",
"P7200" => "P7200",
"700P" => "Jaguar 700p",
"LPE200" => "LPE200",
"XL200" => "XL200"
];
?>
<select name="radio_typ" id="radio_typ" >
<?php foreach ($options as $value => $name) { ?>
<option value="<?= $value; ?>"<?= ($value == $radio_typ) ? ' selected' : ''; ?>><?= $name; ?></option>
<?php } ?>
</select>

How to use a php variable as a value in a select tag? [duplicate]

Is there any way to set the selected item in a drop down box using the following 'type' code?
<select selected="<?php print($row[month]); ?>"><option value="Janurary">January</option><option value="February">February</option><option value="March">March</option><option value="April">April</option></select>
The database holds a month.. and I want to allow on the edit page, them to choose this month.. but it to be pre-filled with their current setting?
You need to set the selected attribute of the correct option tag:
<option value="January" selected="selected">January</option>
Your PHP would look something like this:
<option value="January"<?=$row['month'] == 'January' ? ' selected="selected"' : '';?>>January</option>
I usually find it neater to create an array of values and loop through that to create a dropdown.
You mark the selected item on the <option> tag, not the <select> tag.
So your code should read something like this:
<select>
<option value="January"<?php if ($row[month] == 'January') echo ' selected="selected"'; ?>>January</option>
<option value="February"<?php if ($row[month] == 'February') echo ' selected="selected"'; ?>>February</option>
...
...
<option value="December"<?php if ($row[month] == 'December') echo ' selected="selected"'; ?>>December</option>
</select>
You can make this less repetitive by putting all the month names in an array and using a basic foreach over them.
You can use this method if you use a MySQL database:
include('sql_connect.php');
$result = mysql_query("SELECT * FROM users WHERE `id`!='".$user_id."'");
while ($row = mysql_fetch_array($result))
{
if ($_GET['to'] == $row['id'])
{
$selected = 'selected="selected"';
}
else
{
$selected = '';
}
echo('<option value="'.$row['id'].' '.$selected.'">'.$row['username'].' ('.$row['fname'].' '.substr($row['lname'],0,1).'.)</option>');
}
mysql_close($con);
It will compare if the user in $_GET['to'] is the same as $row['id'] in table, if yes, the $selected will be created. This was for a private messaging system...
Simple and easy to understand example by using ternary operators to set selected value in php
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $id=> $value) { ?>
<option value="<?php echo $id;?>" <?php echo ($id== '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
Its too old but I have to add my way as well :) because it is generic and useful especially when you are using static dropdown values.
function selectdCheck($value1,$value2)
{
if ($value1 == $value2)
{
echo 'selected="selected"';
} else
{
echo '';
}
return;
}
and in you dropdown options you can use this function like this and you can use this as many as you can because it fits with all of your select boxes/dropdowns
<option <?php selectdCheck($row[month],january); ?> value="january">january</option>
:) I hope this function help others
Simple way
<select class ="dropdownstyle" name="category" selected="<?php print($messageeditdetails[0]['category_id']); ?>">
<option value=""><?php echo "Select"; ?></option>
<?php foreach ($dropdowndetails as $dropdowndetails) { ?>
<option <?php if($messageeditdetails[0]['category_id'] == $dropdowndetails['id']) { ?> selected="<?php echo $dropdowndetails['id']; ?>" <?php } ?> value="<?php echo $dropdowndetails['id']; ?>"><?php echo $dropdowndetails['category_name']; ?></option>
<?php } ?>
</select>
This is the solution that I came up with...
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="select_month">
<?php
if (isset($_POST['select_month'])) {
if($_POST["select_month"] == "January"){
echo '<option value="January" selected="selected">January</option><option value="February">February</option>';
}
elseif($_POST["select_month"] == "February"){
echo '<option value="January">January</option><option value="February" selected="selected">February</option>';
}
}
else{
echo '<option value="January">January</option><option value="February">February</option>';
}
?>
</select>
<input name="submit_button" type="submit" value="Search Month">
</form>
A Simple Solution:
It work's for me
<div class="form-group">
<label for="mcategory">Select Category</label>
<select class="form-control" id="mcategory" name="mcategory" required>
<option value="">Please select category</option>
<?php foreach ($result_cat as $result): ?>
<option value="<?php echo $result['name'];?>"<?php
if($result['name']==$mcategory){
echo 'selected';
} ?>><?php echo $result['name']; ?></option>
}
<?php endforeach; ?>
</select>
</div>
Check this:
<select class="form-control" id="department" name="department" type="text">
<option value="medical-furniture" #if($list->department == "medical-furniture") selected #endif>Medical furniture</option>
<option value="medical-table" #if($list->department == "medical-table") selected #endif>Medical table</option>
<option value="service" #if($list->department == "service") selected #endif>Service</option>
</select>
My suggestion is to leverage the hidden/collapse attribute. Try with this example:
<select>
<option value="echo $row[month]" selected disabled hidden><? echo $row[month] ?></option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
</select>
in case of null for $row[month] the selected item is blank and with data, it would contain less codes for many options and always working for HTML5 and bootstrap etc...
If you have a big drop down. it's much easier to use jQuery with PHP.
This is how to do it:
<script>
$(document).ready(function () {
$('select[name="country"]').val('<?=$data[0]['Country']?>');
});
</script>
The easiest solution for the selected option in dropdown using PHP is following
<select class="form-control" name="currency_selling" required >
<option value="">Select Currency</option>
<option value="pkr" <?=$selected_currency == 'pkr' ? ' selected="selected"' : '';?> >PKR</option>
<option value="dollar" <?=$selected_currency == 'dollar' ? ' selected="selected"' : '';?> >USD</option>
<option value="pounds" <?=$selected_currency == 'pounds' ? ' selected="selected"' : '';?> >POUNDS</option>
<option value="dirham" <?=$selected_currency == 'dirham' ? ' selected="selected"' : '';?> >DRHM</option>
</select>
You can try this after select tag:
<option value="yes" selected>yes</option>
<option value="no">no</option>

How to have a value already selected from <select> tag

I have the following dropdown implemented:
<select style="margin-left:25px;">
<option value="null"> </option>
<option value="single">Single</option>
<option value="in_a_relationship">In a relationship</option>
<option value="engaged">Engaged</option>
<option value="married">Married</option>
<option value="open_rel">In an open relationship</option>
<option value="divorced">Divorced</option>
</select>
Say for example, a user has already selected Single from the drop down menu. When they do back to this page, I want single to be already chosen from the list. For text fields I can simply get the value from the database and then assign it to a variable and then echo it in the value. I.e.
$get_data2 = mysqli_query ($connect, "SELECT * FROM user_bio WHERE username = '$username'");
$row3 = mysqli_fetch_assoc ($get_data2);
$bio = $row3['about_me'];
and then do ...
<textarea name="biotextarea" form="change_details" rows="4" cols="60" maxlength="255"><?php echo $bio; ?> </textarea>
How can I do this for a select tag?
Here's how to select the option Single in HTML :
<select style="margin-left:25px;">
<option value="null"> </option>
<option value="single" selected>Single</option>
<option value="in_a_relationship">In a relationship</option>
<option value="engaged">Engaged</option>
<option value="married">Married</option>
<option value="open_rel">In an open relationship</option>
<option value="divorced">Divorced</option>
</select>
So, how to set this in PHP?!
Well, you could generate your <select> element like this :
<?php
$options = [
'null' => ' ',
'single' => Single',
'in_a_relationship' => 'In a relationship',
'engaged' => 'Engaged',
'married' => 'Married',
'open_rel' => 'In an open relationship',
'divorced' => 'Divorced'
];
?>
<select style="margin-left:25px;"><?php
foreach($options as $key => $value) {
echo '<option value="' . $key . '"';
if ($key === $row3['status']){
echo ' selected';
}
echo '>' . $value . '</option>';
}
?></select>
Setting a preselected option on a select tag requires you to put a selected attribute on the selected option.
<select style="margin-left:25px;">
<?php
$options = array(array("null"," "),array("single","Single"),array("in_a_relationship","In a relationship"),array("engaged","Engaged"),array("married","Married"),array("open_rel","In an open relationship"),array("divorced","Divorced"));
foreach ($option in $options){
if ($option[0] == $row3['status']){
$selected = 'selected ';
}
else{
$selected = '';
}
echo '<option '.$selected.'value="'.htmlspecialchars($option[0]).'">'.htmlspecialchars($option[1]).'</option>';
}
?>
</select>
The solution of Musa it's OK, but If you don't want to change your PHP too much
you can do the task with Javascript.
With jQuery or pure Javascript
function selector(id, value){
select = document.getElementById(id);
for(i=0;i<select.options.length;i++){
if(select.options[i].value == value){
select.selectedIndex = i;
}
}
}
//Pure Javascript
selector("status", "engaged")
//With jQuery
jQuery('#status').val('married');
Check this Snippet

How to make dropdown option selected against a variable in php

I have a dropdown like the following.
<select>
<option value="Mr">Mr</option>
<option value="Dr">Dr</option>
<option value="Prof">Prof</option>
</select>
I am getting a value from data base in $selected_value variable. Based on this value I want to make one option from the above select to be selected.
Eg: If $selected_value = Mr, <option value="Mr" selected>Mr</option>
if $selected_value = Dr, <option value="Dr" selected>Dr</option>
update:
now when i am inspecting element i am getting like below.but not selecting Dr.but it is orking in w3schools try editor.
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected="selected">Dr</option>
<option value="Prof">Prof</option>
</select>
update 2
see screen shot:
update3
now it works! added name for <select>
This will work for you problem
try this code
<select>
<option value="Mr" <?=($selected_value=="Mr") ? "selected" : ""?>>Mr</option>
<option value="Dr" <?=($selected_value=="Dr") ? "selected" : ""?>>Dr</option>
</select>
try this..
<option value="Mr" <?php if($selected_value == 'Mr') echo 'selected' ?>>Mr</option>
<option value="Dr" <?php if($selected_value == 'Dr') echo 'selected' ?>>Dr</option>
<option value="Prof" <?php if($selected_value == 'Prof') echo 'selected' ?>>Prof</option>
Or you can use by using jquery
<script>
$('select option[value="<?php echo $selected_value ?>"]').attr('selected','true')
</script>
As per your current HTML use the code below:
<select name="your_select_name">
<option <?php echo (($selected_value=="Mr")?"selected":"") ?> value="Mr">Mr</option>
<option <?php echo (($selected_value=="Dr")?"selected":"") ?> value="Mr">Dr</option>
<option <?php echo (($selected_value=="Prof")?"selected":"") ?> value="Mr">Prof</option>
</select>
If the value of this variable($selected_value) returns "Dr" then 2nd option will be selected. And also give a name of your select tag.
I changed my solution so it fits yours I hope.
UPDATE:
<select name="dropdownlist">
<?
$options = array("Mr", "Dr", "Prof");
foreach($options as $option){
if($_POST['dropdownlist'] == $option){
echo '<option selected="selected">' .$option. '</option>';
}else{
echo '<option>' .$option. '</option>';
}
}
?>
</select>
If you also have an array of your options you could create the option tags by looping through each one of them. In that loop you then can check if the $selected_value matches $option_value like so:
<select>
<?php foreach($options as $option_value => $option_displayName) : ?>
<option
value="<?php echo $option_value; ?>"
<?php echo $option_value == $selected_value ? 'selected' : ''; ?>>
<?php echo $option_displayName; ?>
</option>
<?php endforeach; ?>
</select>
To do what you want you'd have to build the select dynamically like the following example:
<?php
$selects = array(
array('name' => 'Mr', 'value' => 'Mr'),
array('name' => 'Dr', 'value' => 'Dr'),
array('name' => 'Prof', 'value' => 'Prof'),
);
$selected_option = 'Dr';
echo '<select>';
foreach($selects as $select) {
if($select['value'] == $selected_option) {
echo '<option value="'.$select['value'].'" selected>' .$select['name']. '</option>';
} else {
echo '<option value="'.$select['value'].'">' .$select['name']. '</option>';
}
}
echo '</select>';
?>
Which outputs:
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected>Dr</option>
<option value="Prof">Prof</option>
</select>
Example
Try as follows .
<select name="select_options">
<option value="Mr">Mr</option>
<option value="Dr">Dr</option>
<option value="Prof">Prof</option>
</select>
After hit submit button. Then you will get value in $_POST['select_options']
There are many ways to achieve what you're doing. I can think of two straight ways to do this.
The first is ugly:
Insert in each option a php tag and check if value is selected:
<select>
<option <?php if ($selected_value == 'Mr') echo 'selected'; ?> value="Mr">Mr</option>
<option <?php if ($selected_value == 'Dr') echo 'selected'; ?> value="Dr">Dr</option>
<option <?php if ($selected_value == 'Prof') echo 'selected'; ?> value="Prof">Prof</option>
</select>
Otherwise, I would personally write a little helper
function generateSelect(array $entries, $selected)
{
$ret = '<select>'
foreach ($entries as $entry) {
$ret .= '<option';
if ($entry == $selected) {
$ret .= ' selected';
}
$ret .= ' value="'.$entry.'"';
$ret .= '>'.$entry.'</option'>;
}
return $ret;
}
It is just an example and its functionality could be expanded. It SHOULD work, but I haven't tried it myself (wrote it quickly)
You have mistaken syntax
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected="selected">Dr</option>
<option value="Prof">Prof</option>
</select>
this will work
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected>Dr</option>
<option value="Prof">Prof</option>
</select>

A better solution to handle PHP and HTML <option> logic

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

Categories