I have a form that fetches user info into the $row variable so forms are populated if the row exists if the database, but then saves any new input through the $_POST global variable, in case the user makes a mistake elsewhere on the form. It all works great.
<label for="qualification2">Grade:</label>
<input type="text" name="qualification2" id="grade2" class="form-control"
value="<?php if(isset($_POST['qualification2'])) {
echo $_POST['qualification2'];
} else { echo ($row ['qualification2']); } ?>">
I would like to do similar using a selection dropdown box but the code doesn't seem to work the same with dropdown boxes and I wonder what I'm doing wrong or if this is even possible.
I've also tried echo from the $row variable but that doesn't work either
<?php if($row['qualMonth2'] == 'February') { echo ' selected'; } ?>
This is my code:
<select input type="text" name="qualMonth2" id="qualMonth2" value="Select Month">
<option value="January" <?php if(isset($_POST['qualMonth2']) == 'January') { echo ' selected'; } ?>>January</option>
<option value="February" <?php if(isset($_POST['qualMonth2']) == 'February') { echo ' selected'; } ?>>February</option>
<option value="March" <?php if(isset($_POST['qualMonth2']) == 'March') { echo ' selected'; } ?>>March</option>
<option value="April" <?php if(isset($_POST['qualMonth2']) == 'April') { echo ' selected'; } ?>>April</option>
<option value="May" <?php if(isset($_POST['qualMonth2']) == 'May') { echo ' selected'; } ?>>May</option>
<option value="June" <?php if(isset($_POST['qualMonth2']) == 'June') { echo ' selected'; } ?>>June</option>
<option value="July" <?php if(isset($_POST['qualMonth2']) == 'July') { echo ' selected'; } ?>>July</option>
<option value="August" <?php if(isset($_POST['qualMonth2']) == 'August') { echo ' selected'; } ?>>August</option>
<option value="September" <?php if(isset($_POST['qualMonth2']) == 'September') { echo ' selected'; } ?>>September</option>
<option value="October" <?php if(isset($_POST['qualMonth2']) == 'October') { echo ' selected'; } ?>>October</option>
<option value="November" <?php if(isset($_POST['qualMonth2']) == 'November') { echo ' selected'; } ?>>November</option>
<option value="December" <?php if(isset($_POST['qualMonth2']) == 'December') { echo ' selected'; } ?>>December</option>
</select>
isset validates to true or false based on if variable is set or not. You can't check the value just with isset.
Use a small utility function to check condition:
function checkSelected($value) {
if(isset($_POST['qualMonth2']) && $_POST['qualMonth2'] == $value) {
return true;
} else {
return false;
}
}
Your select element should be then:
<select input type="text" name="qualMonth2" id="qualMonth2" value="Select Month">
<option value="January" <?php echo checkSelected('January') ? 'selected':'' ?>>January</option>
<option value="February" <?php echo checkSelected('February') ? 'selected':'' ?>>February</option>
<option value="March" <?php echo checkSelected('March') ? 'selected':'' ?>>March</option>
<option value="April" <?php echo checkSelected('April') ? 'selected':'' ?>>April</option>
<option value="May" <?php echo checkSelected('May') ? 'selected':'' ?>>May</option>
<option value="June" <?php echo checkSelected('June') ? 'selected':'' ?>>June</option>
<option value="July" <?php echo checkSelected('July') ? 'selected':'' ?>>July</option>
<option value="August" <?php echo checkSelected('August') ? 'selected':'' ?>>August</option>
<option value="September" <?php echo checkSelected('September') ? 'selected':'' ?>>September</option>
<option value="October" <?php echo checkSelected('October') ? 'selected':'' ?>>October</option>
<option value="November" <?php echo checkSelected('November') ? 'selected':'' ?>>November</option>
<option value="December" <?php echo checkSelected('December') ? 'selected':'' ?>>December</option>
</select>
Lets look at what you wrote..
<option value="February" <?php if(isset($_POST['qualMonth2']) == 'February') { echo ' selected'; } ?>>February</option>
What you're saying is.. If there is a value set for qualMonth2 (true / false), compare that against a string..
So you're comparing true || false against a string.
isset($_POST['qualMonth2']) returns true // false.
So none will ever be selected.
Refactor it..
<?php
$month = "";
if(isset($_POST['qualification2'])){
$month = $_POST['qualification2'];
}
?>
Then use $month as the comparative value.
<option value="July" <?php if($month == 'July') { echo ' selected'; } ?>>July</option>
I prefer to perform these checks in Javascript (I prefer JQuery), I think it cleans up the code, but you could also simplify this greatly by using a loop with generated months.
Loop through 1-12 for output
<select input type="text" name="qualMonth2" id="qualMonth2" value="Select Month">
<?php
for($i=1; $i<=12; $i++) {
$dateObj = DateTime::createFromFormat('!m', $i);
$monthName = $dateObj->format('F');
echo "<value>" . $monthName . "</option>";
}
?>
</select>
This approach takes a DRY (Do not repeat) approach. If you need to modify something, you only need to modify 1 line of code versus 12.
Jquery for choosing value (defaults to January if $_POST['qualMonth2'] is not set):
<script>
$('#qualMonth2').val("<?php echo (isset($_POST['qualMonth2'])) ? $_POST['qualMonth2'] : 'January' ?>");
</script>
Take what you will from this answer, I just showed you two possibilities, you can certainly avoid Javascript by adding a check in the loop if you want.
Related
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>
I have problem with my codes and I'm still new to php. Please help me :)
echo "<td><select>
<option value='1'<?php if($row['Staf_Kamp'] == '1') { ?> selected='selected'<?php } ?>>1</option>;
<option value='2'<?php if($row['Staf_Kamp'] == '2') { ?> selected='selected'<?php } ?>>2</option>;
<option value='3'<?php if($row['Staf_Kamp'] == '3') { ?> selected='selected'<?php } ?>>3</option>;
</select></td>";
I am expecting the dropdown list that I have selected before edit will be selected in the edit page. But it is not working.
When echoing, you are already in a php context, so there is no need to use <?php ?> tags again. You can just concatenate the variables in your string.
echo "<td><select>
<option value='1'" . ($row['Staf_Kamp'] == '1' ? ' selected="selected"' : '') . ">1</option>;
<option value='2'" . ($row['Staf_Kamp'] == '2' ? ' selected="selected"' : '') . ">2</option>;
<option value='3'" . ($row['Staf_Kamp'] == '3' ? ' selected="selected"' : '') . ">3</option>;
</select></td>";
Try this:
<td><select>
<option value='1'<?php if($row['Staf_Kamp'] == '1') { echo ' selected'; } ?>>1</option>
<option value='2'<?php if($row['Staf_Kamp'] == '2') { echo ' selected'; } ?>>2</option>
<option value='3'<?php if($row['Staf_Kamp'] == '3') { echo ' selected'; } ?>>3</option>
</select></td>
You only need ; when working inside the <?php ?> tags so strip those out. Also save the opening and closing by just echoing out the selected value. Also the correct syntax is selected and not selected='selected'
you can not echo a string and put php code into the string
correct code:
<td>
<select>
<option value='1'<?php if($row['Staf_Kamp'] == '1') { ?> selected='selected'<?php } ?>>1</option>
<option value='2'<?php if($row['Staf_Kamp'] == '2') { ?> selected='selected'<?php } ?>>2</option>
<option value='3'<?php if($row['Staf_Kamp'] == '3') { ?> selected='selected'<?php } ?>>3</option>
</select>
</td>
Iam using PHP codeigniter framework. Value is set to select dropdown as below
<select class="form-control";>
<option <?php if($d1 == 'native') { echo 'selected'; }?> value='native' >native</option>
<option <?php if($d1 == 'migrated') { echo 'selected'; }?> value='migrated' >migrated</option>
</select>
for each row in table there is select option like above. I want to highlight option with color if option is set to migrated on page load.
I tried like below
<select class="form-control";>
<option <?php if($d1 == 'native') { echo 'selected'; }?> value='native' >native</option>
<option <?php if($d1 == 'migrated') { echo 'selected'; echo 'style="<color:red>"' }?> value='migrated' >migrated</option>
</select>
Your are not using proper syntax for style; you are missing a semicolon; and selected and style will be together making it useless. Try:
<select class="form-control">
<option <?php if($d1 == 'native') { echo 'selected'; }?> value='native' >native</option>
<option <?php if($d1 == 'migrated') { echo 'selected style="background-color:red"' }?> value='migrated' >migrated</option>
</select>
Although to me it is easier to read inline conditions as the following:
<select class="form-control">
<option <?php echo $d1 == 'native' ? 'selected' : ''; }?> value='native' >native</option>
<option <?php echo $d1 == 'migrated' ? 'selected style="background-color:red"' : ''; }?> value='migrated' >migrated</option>
</select>
your styling is wrong
<select class="form-control";>
<option <?php if($d1 == 'native') { echo 'selected'; }?> value='native' >native</option>
<option <?php if($d1 == 'migrated') { echo 'selected'; echo 'style="color:red"'; }?> value='migrated' >migrated</option>
</select>
you don't need the brackets <> inside the inline style and don't forget semicolon ;
i would like this select filter to show up only if Language count is more than 4
Any ideas?
Here is html select filter code:
<p>
Select date:
</p>
<form method="get" action="">
<select id="training_session" name="date"onchange=this.form.submit()>
<option value=""<?php if($_GET['date'] === '') echo 'selected' ?>>[All dates]</option>
<option value="April"<?php if($_GET['date'] === 'April') echo 'selected' ?>>April</option>
<option value="May"<?php if($_GET['date'] === 'May') echo 'selected' ?>>May</option>
<option value="June"<?php if($_GET['date'] === 'June') echo 'selected' ?>>June</option>
<option value="July"<?php if($_GET['date'] === 'July') echo 'selected' ?>>July</option>
<option value="August"<?php if($_GET['date'] === 'August') echo 'selected' ?>>August</option>
<option value="September"<?php if($_GET['date'] === 'September') echo 'selected' ?>>September</option>
<option value="October"<?php if($_GET['date'] === 'October') echo 'selected' ?>>October</option>
<option value="November"<?php if($_GET['date'] === 'November') echo 'selected' ?>>November</option>
</form>
<noscript><input type="hidden" value="filter"></noscript>
Here is PHP code:
if (isset($_GET['date']) && $_GET['date']) {
foreach ($training_sessions as $key => $session) {
if (date('F', strtotime($session['ZCS_b_date'])) !== $_GET['date']) {
unset($training_sessions[$key]);
So how do i make it to show up only if language count is more than 4. I have language select filter which has to stay there all the time, but i want date filter to show up only if language count is more than 4.
This is the language select filter code:
<p>
Select language:
</p>
<form method="get" action="">
<select id="training_session" name="lang" onchange=this.form.submit()>
<option value=""<?php if($_GET['lang'] === '') echo 'selected' ?>>[All languages]</option>
<option value="English" <?php if($_GET['lang'] === 'English') echo 'selected' ?>>English</option>
<option value="Portuguese"<?php if($_GET['lang'] === 'Portuguese') echo 'selected' ?>>Portuguese</option>
<option value="French"<?php if($_GET['lang'] === 'French') echo 'selected' ?>>French</option>
<option value="Italian"<?php if($_GET['lang'] === 'Italian') echo 'selected' ?>>Italian</option>
<option value="Japanese"<?php if($_GET['lang'] === 'Japanese') echo 'selected' ?>>Japanese</option>
</form>
<noscript><input type="hidden" value="filter"></noscript>
This is the php code for language select filter:
if (isset($_GET['lang']) && $_GET['lang']) {
foreach ($training_sessions as $key => $session) {
if ($session['training_language'] !== $_GET['lang']) {
unset($training_sessions[$key]);
So does anyone knows what im trying to achieve here? What i want to do.
Ok here we go..
This should give you the results you want
<html>
<head></head>
<body>
<form id="submitquery" method="get" action="">
<?php
$month=array('[All Dates]','January','February','March','April',
'May','June','July','August',
'September','October','November','December');
$language=array('[All Languages]','English','Portuguese','French','Italian','Japanese');
$changeLanguagejs='changeForm();';
$changeDatejs='this.form.submit();';
writeSelect($language,'Language',$changeLanguagejs);
if (isset($_GET['Language'])){
if($_GET['Language']!='[All Languages]'){
$training_sessions=filterLanguage($training_sessions);}
if (count($training_sessions)>=4){
writeSelect($month,'Date',$changeDatejs);
if (isset($_GET['Date'])){
if($_GET['Date']!='[All Dates]'){
$training_sessions=filterDate($training_sessions);}
showResults($training_sessions);}}
else{showResults($training_sessions);}}
?>
</form>
</body>
</html>
<?php
function writeSelect($values,$name,$changejs){
echo "\n".'<p>Select '.$name.':</p>';
echo "\n".' <select id="training_sessions_'.$name.'" name="'.$name.'" onchange='.$changejs.'>'."\n";
foreach($values as $value){
echo ' <option value="'.$value.'" ';
if (isset($_GET[$name]) && $_GET[$name]==$value){echo 'selected ';}
echo '>'.$value.'</option>'."\n";}
echo ' </select><br/><br/>'."\n";}
function filterLanguage($training_sessions){
foreach($training_sessions as $key => $session){
if($session['training_language']!=$_GET['Language']){
unset($training_sessions[$key]);}}
return $training_sessions;}
function filterDate($training_sessions){
foreach($training_sessions as $key => $session){
if(date('F', strtotime($session['ZCS_b_date']))!=$_GET['Date']){
unset($training_sessions[$key]);}}
return $training_sessions;}
function showResults($training_sessions){
echo "\n".'Showing '.count($training_sessions).' ';
if(count($training_sessions)==1){echo 'Result';}
else{echo 'Results';}
echo'<br/>'."\n\n";
print_r($training_sessions);}
?>
<script>
function changeForm(){
var selectLang = document.getElementById("training_sessions_Language").value;
document.getElementById("submitquery").method="post";
document.getElementById("submitquery").action="?Language="+selectLang;
document.getElementById("submitquery").submit();}
</script>
I'm going to edit out the comments to make it more readable...
if you want to see the comments go back through the edits of this answer
I have simple code
File name:newEmptyPHP.php
<form method="post" action="newEmptyPHP.php">Title:
<select name="title">
<option value="select">Select</option>;
<option value="Dr" selected=<?php if(isset($_POST[ 'title'])=="Dr" ){ echo "selected"; } ?>>Dr</option>';
<option value="Prof">Prof</option>';
<option value="Mr">Mr</option>';
<option value="Ms">Ms</option>';
<option value="Miss">Miss</option>';
<option value="Mrs">Mrs</option>';</select>
<input type="submit" value="submit">
</form>
I want to keep selected particular value which was selected before the form submission.
But i did not get the desirable output.
any help appreciated.
change this
<option value="Dr" selected=<?php if(isset($_POST['title']) == "Dr")
{ echo "selected"; } ?> >Dr</option>';
to
<option value="Dr" <?php if(isset($_POST['title']) && $_POST['title'] == "Dr")
{ echo "selected='selected'"; } ?> >Dr</option>';
<?php if(isset($_POST['title']) == "Dr"){ echo "selected"; } ?>
Change to
<?php if(isset($_POST['title']) && $_POST['title'] == "Dr"){ echo "selected"; } ?>
But better to use JS / jQuery. Example for jQuery:
<?php if(isset($_POST['title']) && $_POST['title'] == "Dr"):?>
<script type="text/javascript">
$(function(){
$('select[name=title]').val('<?php echo html_special_chars($_POST[''title'])?>');
});
</script>
<?php endif?>
<?php
if($_POST['title'] == "Dr")
{ ?>
<option value="Dr" selected>Dr</option>
<?php
}
else
{
?>
<?php
<option value="Dr">Dr</option>
<?php
}
?>
Change
<option value="Dr" selected=<?php if(isset($_POST['title']) == "Dr"){ echo "selected"; } ?> >Dr</option>';
To :
<option value="Dr" <?php if(isset($_POST['title']) && $_POST['title'] == "Dr"){ echo 'selected="selected"'; } ?> >Dr</option>';
1.Remove isset where you are checking it for value, isset will return either true or false
2.Make selected="selected inside if condition
There is a mistake in your code. isset(Something) will return either true or false and will not return Dr you are looking for.
Retry with this
<form method="post" action="newEmptyPHP.php">
Title:<select name="title" >
<option value="" >Select</option>
<option value="Dr" selected=<?php if(isset($_POST['title']) && $_POST['title'] == "Dr"){ echo "selected"; } ?> >Dr</option>';
<option value="Prof" <?php if(isset($_POST['title']) && $_POST['title'] == "Prof"){ echo "selected"; } ?>>Prof</option>';
<option value="Mr" <?php if(isset($_POST['title']) && $_POST['title'] == "Mr"){ echo "selected"; } ?>>Mr</option>';
<option value="Ms" <?php if(isset($_POST['title']) && $_POST['title'] == "Ms"){ echo "selected"; } ?>>Ms</option>';
<option value="Miss" <?php if(isset($_POST['title']) && $_POST['title'] == "Miss"){ echo "selected"; } ?>>Miss</option>';
<option value="Mrs" <?php if(isset($_POST['title']) && $_POST['title'] == "Mrs"){ echo "selected"; } ?>>Mrs</option>';
</select>
<input type="submit" value="submit">
I thin you have static option values.If so the you have to check for every option like as below for one.
<form method="post" action="newEmptyPHP.php">
Title:<select name="title" >
<option value="select" >Select</option>;
<?php
$selected = "";
if(isset($_POST['title']) && $_POST['title'] == "Dr")
{
$selected = 'selected="selected"';
}
?>
<option value="Dr" <?php echo $selected; ?>>Dr</option>
<option value="Prof">Prof</option>
<option value="Mr">Mr</option>
<option value="Ms">Ms</option>
<option value="Miss">Miss</option>
<option value="Mrs">Mrs</option>
</select>
<input type="submit" value="submit">
</form>
I would rather prefer this code for the purpose
$option_array = array('select'=>'select','mr'=>'mr'... other values);
<?php
$option_string = '';
foreach($option_array as $key=>$value)
{
if($key == $_POST['title'])
{
$selected = 'selected';
}
else
{
$selected = '';
}
$option_string .= "<option value='$key' $selected>$value</option>";
}
?>
<form method="post" action="newEmptyPHP.php">Title:
<select name="title">
<?php echo $option_string; ?>
</select>
<input type="submit" value="submit">