How to set selected value in drop list in HTML? - php

How to set selected value in drop list in HTML in Edit Form?
The selected value came from MySql
This code is not work !! >> selected=""
<select name="TutorGender" id="TutorGender" selected="<?php echo $Gender ?>">
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>

W3Schools does a good job of explaining this here
http://www.w3schools.com/tags/att_option_selected.asp
Your code might look something like this.
<select name="TutorGender" id="TutorGender">
<option value="Male" <?php if($Gender == "Male") echo "selected"; ?>>Male</option>
<option value="Female" <?php if($Gender == "Female") echo "selected"; ?>>Female</option>
</select>
Though my PHP syntax may be a little off, but you should get the idea.

Selected goes on the option tag, not on the select tag.
<select name="TutorGender" id="TutorGender" >
<option value="Male" selected="selected">Male</option>
<option value="Female">Female</option>
</select>

<select name="TutorGender" id="TutorGender">
<option value="Male" <?php if($Gender=='Male') echo 'selected' ?>>Male</option>
<option value="Female" <?php if($Gender=='Female') echo 'selected' ?>>Female</option>
</select>

The selected attribute appears on the option(s) that should be selected, not the select element (if it went on the select element itself, then (since multiple options can be selected at the same time) it would have to take a list of ids and you would need to add an id to each option).
<option value="foo" selected>Foo</option>
Generally you would have an array of values (or of value/human text pairs) that you would loop over. (i.e. you wouldn't hard code your options)
You would generate one option each time you went around the loop, and test to see if you should include a selected attribute each time.

<option <?php if($Gender == 'Male'){ echo(' selected '); } ?> value="Male">Male</option>
<option <?php if($Gender == 'Female'){ echo(' selected '); } ?> value="Female">Female</option>

<select name="TutorGender" id="TutorGender">
<?php
$genders = array( 'Male', 'Female' );
foreach( $genders as $value )
{
$selected = ( $Gender == $value )? ' selected="selected"': '';
echo '<option value="' . $value . '"' . $selected . '>' . $value . '</option>';
}
?>
</select>

just another way of doing it. I prefer to use shorthand if statements for code such as this.
<select name="TutorGender" id=\"TutorGender\">
<option value="Male" <?php echo ($Gender == "Male" ? "selected" : ""); ?>>Male</option>
<option value="Female" <?php echo ($Gender == "Female" ? "selected" : ""); ?>>Female</option>
here is a link to using shorthand "if" statements.

In a case where I needed to use a select as part of a user update form that was populated via a database I found the array option works best. The line by line option can get very unwieldy very quickly. This way you simply need to add an option to the $optionDept array should any new options be required. In this example "$row['Dept']" is from the larger overarching results from the database request.
$optionDept= array('sales','warehouse','inspection','production','accounts','admin','inactive');
$optionCount= count($optionDept);
echo"<select name=\"UserDept\">";
for($x = 0; $x < $optionCount; $x++) {
echo"<option value=".$optionDept[$x];
if($optionDept[$x]==$row['Dept']){echo " selected";}
echo">".$optionDept[$x]."</option>";}
echo"</select</P>

try this
if you want to keep male as selected
<select name="TutorGender" id="TutorGender" >
<option value="Male" selected="selected">Male</option>
<option value="Female">Female</option>
</select>

This worked for me: I send througt the GET method of the submit the value i want to restore, and then in the php, AT THE END OF THE PAGE (if not, default values will be set if the code is before the php) i set those values.
echo "select_language.selectedIndex = ".$_GET['iL'].";";

Related

PHP If variable equals value in dropdown then add 'selected' attribute to option

I have a drop down menu that checks whether a user has already selected a value by checking database and if they have, I want to add a 'selected' attribute to that option so that when they edit their profile, that option is preselected by what they chose.
Heres an example of what I am trying to accomplish. It works for text inputs but I don't know how to do it with dropdown lists.
So if user selects 'Dog', it gets place in database and adds 'selected' as attribute
$animal = $mysqli->escape_string($_POST['animal']);
//PHP UPDATE database script -------->
<label>Animal</label></br>
<select name='animal' value='<?php if($animal == value){ /*Add selected attribute to option */ ?>'>
<option value="" disabled selected>Select One</option>
<option value="" disabled>----------------</option>
<option value="Dog">Dog</option>
<option value="Cat">Cat</option>
<option value="Bird">Bird</option>
</select>
Define an array of options
$animals = ['Dog', 'Cat', 'Bird'];
Then generate the list of options for the <select> from that array, checking the selected animal against each one. If it matches, then add the selected attribute.
<label>Animal</label></br>
<select name='animal'>
<!-- select the default if none of the options are selected -->
<option value="" disabled <?php if (!in_array($animal, $animals)) echo 'selected' ?>>
Select One
</option>
<option value="" disabled>----------------</option>
<?php foreach ($animals as $option) {
echo "<option ";
if ($animal == $option) {
echo 'selected';
}
echo ">$option</option>";
?>
</select>
value attributes aren't required for your <option> elements in this case, since you're using the same values for the option text. (If the value attribute is omitted, the option text will be used as the value.)
Try it like this:
$animal = $mysqli->escape_string($_POST['animal']);
//PHP UPDATE database script -------->
echo '<label>Animal</label></br>
<select name="animal">
<option value="" disabled>Select One</option>
<option value="" disabled>----------------</option>
<option value="Dog" ' . ($animal == 'Dog' ? 'selected' : '') . '>Dog</option>
<option value="Cat" ' . ($animal == 'Cat' ? 'selected' : '') . '>Cat</option>
<option value="Bird" ' . ($animal == 'Bird' ? 'selected' : '') . '>Bird</option>
</select>';

Whats the best way to show selected options on a form when reloaded using PHP

I would like the select option the user selected to be shown when the form is reloaded. I am currently using bootstrap select picker to style the drop down. Right now I am creating an array and echoing out a selected class based on the value stored in the database.
This is not a major problem with a small amount of options like the code provided below, however with a select box with larger amounts of options this obviously amounts to lots of extra code.
There must be a smarter way to do this than the code i'm using below. Can anyone help?
<select class="selectpicker" name="Do_You_Have_A_Job_Spec_You_Can_Email">
<option value="" <?php if ($user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'] == '') echo "selected='selected'"; ?>>Please Select</option>
<option value="Yes" <?php if ($user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'] == 'Yes') echo "selected='selected'"; ?>>Yes</option>
<option value="No" <?php if ($user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'] == 'No') echo "selected='selected'"; ?>>No</option>
</select>
If the option's are static you could use ternary operators, so it will be something like :
<?php $selected_option = $user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email']; ?>
<select class="selectpicker" name="Do_You_Have_A_Job_Spec_You_Can_Email">
<option value="" <?php echo $selected_option==''?'selected':''; ?>>Please Select</option>
<option value="Yes" <?php echo $selected_option=='Yes'?'selected':''; ?>>Yes</option>
<option value="No" <?php echo $selected_option=='No'?'selected':''; ?>>No</option>
</select>
Hope this helps.
<?php
$text = $user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'];
?>
<select class="selectpicker" name="Do_You_Have_A_Job_Spec_You_Can_Email">
<option value="">Please Select</option>
<option value="Yes" <?php echo $text == 'Yes' ? 'selected' : ''; ?>> Yes </option>
<option value="No" <?php echo $text == 'No' ? 'selected' : ''; ?>> No </option>
</select>
Alternative Way
"..however with a select box with larger amounts of options this
obviously amounts to lots of extra code.".
In this case, when you are having lots of data for dropdown. You can create a table where you can have both option name and option value.
job_specification_table
id option_value option_name
1 Please Select
2 Yes Yes
3 No No
.
.
.
Then, retreive those values and check for user_data and according to it, option will get selected.
<?php
$sql = "SELECT * FROM job_specification_table";
$result = mysqli_query($db_con,$sql);
$text = $user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'];
?>
<select class="selectpicker" name="Do_You_Have_A_Job_Spec_You_Can_Email">
<?php
while ($row = mysqli_fetch_array($result)){
$option_value = $row['option_value'];
$selected = ($option_value == $text) ? "selected" : "";
?>
<option value="<?=$option_value;?>" <?=$selected;?>>
<?=$row['option_name'];?>
</option>
<?php }?>
</select>
Here is more readable solution:
<select class="selectpicker" name="Do_You_Have_A_Job_Spec_You_Can_Email">
<option value=
<?php
$choise = $user_data_array['Do_You_Have_A_Job_Spec_You_Can_Email'];
switch ($choise) {
case 'Yes':
echo '"Yes" selected="selected" >Yes';
break;
case 'No':
echo '"No" selected="selected" >No';
break;
case '':
echo '"" selected="selected" >Please Select';
break;
}
?>
</option>
</select>

Choose correct Select option from MySQL Database

I have this HTML/PHP Code that lists options in a select element.
Whats the best way to make the correct option selected based on a record from a MySQL database:
This works fine, but is there any easier way to do it with one line of code rather than doing an if statement per option?
<select name="status" id="status">
<option value="Open"<?php if($ticket["status"]=="Open"){echo('selected="selected"');}?>>Open</option>
<option value="Needs Action"<?php if($ticket["status"]=="Needs Action"){echo('selected="selected"');}?>>Needs Action</option>
<option value="Customer Reply"<?php if($ticket["status"]=="Customer Reply"){echo('selected="selected"');}?>>Customer Reply</option>
<option value="Completed"<?php if($ticket["status"]=="Completed"){echo('selected="selected"');}?>>Completed</option>
</select>
use an array:
echo "<select name='status' id='status'>";
$statuses = array('Open', 'Needs Action', 'Customer Reply', 'Completed');
foreach ($statuses as $status) {
echo "<option value='$status' " . ($ticket['status'] == $status) ? "selected='selected'" : "" . "/>";
}
echo "</select>";
You may want to put those values in the database or if you want to avoit it, just put them into an array and print all the options using a loop and mark as selected the right one.
Yes, the code can be shorter (and much more readable):
if($ticket["status"]=="Open") {
$openSelected = "selected='selected'";
}
if($ticket["status"]=="Needs Action") {
$needsActionSelected = "selected='selected'";
}
if($ticket["status"]=="Customer Reply") {
$customerReplySelected = "selected='selected'";
}
if($ticket["status"]=="Completed") {
$completedSelected = "selected='selected'";
}
<select name="status" id="status">
<option value="Open" <?php print($openSelected) ?>>Open</option>
<option value="Needs Action"<?php print($needsActionSelected) ?>>Needs Action</option>
<option value="Customer Reply"<?php print($customerReplySelected) ?>>Customer Reply</option>
<option value="Completed"<?php print($completedSelected) ?>>Completed</option>
</select>
EDIT// #Barmar has a better answer.

drop down list keep previous selected value in php

I have created a profile page in php where a user using an html drop down list chooses gender.
The html code is the following:
Gender<select name="gender">
<option value=" "> EMPTY </option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
After the user chooses gender the form dispatches and saves the data into database. All I want is that the next time that the user visits the profile page, the drop down list to keep the value that the user selected before. For example if user selected in drop down list "male", next time he visited profile page to make changes, the drop down list must show "male" as selected value(keeping it from previous time). Any idea how to do this in PHP?
There is a pretty simplistic way to do this if you are using a form. Also, you probably want to use isset() in case it is the first time they visited the page.
<select name="gender">
<option value="male" <?php echo isset($_GET["gender"]) && $_GET["gender"] == "male" ? "selected" : "" ?>>Male</option>
<option value="female" <?php echo isset($_GET["gender"]) && $_GET["gender"] == "female" ? "selected" : "" ?>>Female</option>
</select>
All this does is insert "selected" into the option tag if the $_GET variable is set and the last one was that specific option. Hope this helps!
What you need to do is give the selected attribute to the option. Assuming you store profile information on the session and have short-tags enabled on your server, you can do something like this:
Gender: <select name="gender">
<option value=" "> Not Selected </option>
<option value="Male"<?=$_SESSION['gender'] == "Male" ? ' selected="selected"' : ''?>>Male</option>
<option value="Female"<?=$_SESSION['gender'] == "Female" ? ' selected="selected"' : ''?>>Female</option>
</select>
You must read the database and add a php script like:
<option value="Male" <?php
if ($gender == "Male") { echo " selected"; }
?>>Male</option>
<option value="Female" <?php
if ($gender == "Female") { echo " selected"; }
?>>Female</option>

Setting the selectedindex property of an HTML dropdown using PHP

From the database I pull back the user information and based on this I can determine the correct index value using a case statement:
<?php
$genderIndex = 0;
switch ($displayProperties['gender'])
{
case "":
$genderIndex = 0;
break;
case "Male":
$genderIndex = 1;
break;
case "Female":
$genderIndex = 2;
break;
case "Other":
$genderIndex = 3;
break;
}
?>
On the form I have an HTML dropdown (select):
<select name="gender" selectedIndex="<?php echo $genderIndex; ?>">
<option value="0"> </option>
<option value="Male">Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select><br/>
The problem is it never works and always loads the page at index=0 and I made sure to verify if $genderIndex actually has the expected value (it does).
What am I doing wrong?
selectedindex property is not used in this way, for appropriate use of the selectedindex property you can view http://www.w3schools.com/jsref/prop_select_selectedindex.asp.
Instead what you are after is applying the "selected" attribute to the appropriate option. The code below runs some shorthand if/else checks and will apply the "selected" attribute where appropriate, based on your $genderIndex you created in your function given.
<select name="gender">
<option value="0" <?php echo ($genderIndex==0)?('selected'):(''); ?>"> </option>
<option value="Male" <?php echo ($genderIndex==1)?('selected'):(''); ?>>Male</option>
<option value="Female" <?php echo ($genderIndex==2)?('selected'):(''); ?>>Female</option>
<option value="Other" <?php echo ($genderIndex==3)?('selected'):(''); ?>>Other</option>
</select><br/>
The reason this is not working is because selectedIndex is not a valid attribute on the HTML <select/> element. (See http://www.w3.org/TR/html4/interact/forms.html#h-17.6)
To pre-select an option in the <select/> element (other than the first one, in this an empty value), you need to have your HTML output look something like this:
<select name="gender">
<option value="0"> </option>
<option value="Male">Male</option>
<option value="Female" selected="true">Female</option>
<option value="Other">Other</option>
</select>
Notice the addition of the selected="true" on the second <option/> tag. Something like the following will get the job done but is hardly elegant.
<select name="gender">
<?php
if(0 == $genderIndex)
echo '<option value="0" selected="true"> </option>';
else
echo '<option value="0"> </option>';
if(1 == $genderIndex)
echo '<option value="Male" selected="true">Male</option>';
else
echo '<option value="Male">Male</option>';
if(2 == $genderIndex)
echo '<option value="Female" selected="true">Female</option>';
else
echo '<option value="Female">Female</option>';
if(3 == $genderIndex)
echo '<option value="Other" selected="true">Other</option>';
else
echo '<option value="Other">Other</option>';
?>
</select>
A good web framework can be helpful here. I know that in Java, the Struts framework assists with echoing a <select/> tag to the output with the appropriate <option/> selected.
That's not how you specify the selected <option> in HTML. You need to have the selected attribute on the <option> itself, like so:
<select name="gender">
<option value="0"> </option>
<option value="Male" selected>Male</option>
<option value="Female">Female</option>
<option value="Other">Other</option>
</select><br/>

Categories