To make dropdown selected while fetching dynamically - php

To make dropdown ticked while fetching dynamically from db.Fetch all values from db and list as dropdown.If the values from db matches particular value make that dropdown selected
<select id="designation" name="designation">
<? while($role=mysql_fetch_array($sql_role)){
if ($role['role'] == $desig ) echo $selected="selected"; else $selected=" ";?>
<option <?=$selected?>>Select</option>
<option value="<?=$role['id']?>"
<?=$selected?> >
<?=$role['role']?>
</option>
<? } ?>
</select>

You are echoing $selected in your check. I also recommend not to use php short tags because it may be deprecated in future PHP versions.
I recommend this code:
$html = '<select id="designation" name="designation">';
$html .= '<option>Select</option>';
while($role = mysql_fetch_array($sql_role))
{
$selected = ($role['role'] == $desig) ? ' selected' : '';
$html .= '<option value="'. $role['id'] .'"'. $selected .'>'. $role['role'] .'</option>';
}
$html .= '</select>';
echo $html;
Don not forget to assign $desig ;-).

Why don't you make the following changes and try. You can totally eliminate the intermediate variable storage. Just print selected if the condition matches. And also you should just put that default select option outside the while loop.
<select id="designation" name="designation">
<option>Select</option>
<? while($role=mysql_fetch_array($sql_role)){ ?>
<option value="<?=$role['id']?>" <? if ($role['role'] == $desig ) echo "selected='selected'"?> ><?=$role['role']?></option>
<? } ?>
</select>

try to avoid short scripts in php like this
<select id="designation" name="designation">
<? while($role=mysql_fetch_array($sql_role)){
<option <?php if ($role['role'] == $desig ) { ?> selected <?php } ?> ><?php echo $role['role']; ?></option>
<? } ?></select>

Related

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>

looping inside a select tag and echo selected value

I am trying to loop inside a select tag and output the quantity inorder to allow the user to select a quantity from the selection box , but the numbers are printed next to each other ,,how to solve that ? ,,and how to echo the selected item !?
<select name="quantity">
<div style="font-
size:13px;position:relative;left:10px;width:80px;height:20px;border-style:
hidden;background-color:rgba(0, 0, 0, 0.50);color:white;" > </div>
<option value="" disabled selected>Quantity </option>
<option value="quantity"><?php for($i=1;$i<=$row["item_quantity"];$i++)
{echo
$i."<br>";}?></option>
</select>
Instead of this:
<option value="quantity"><?php for($i=1;$i<=$row["item_quantity"];$i++)
{echo
$i."<br>";}?></option>
try this:
for($i=1;$i<=$row["item_quantity"];$i++)
{
// To make a option selected
$selected = '';
if( $i == 2 ) // 2 or any value
{ $selected = 'selected="selected"'; }
echo '<option value="'. $i .'" '.$selected.' >'. $i .'</option>'
}
Explanation: The issue is, your loop is inside the option tag, which is wrong. Put the option tag inside the loop.
Check your script you have add loop at wrong place
for($i=1;$i<=$row["item_quantity"];$i++)
{
echo '<option value="'. $i .'">'. $i .'</option>'
}
TRY THIS
<select name="quantity">
<option value="" selected>Quantity </option>
<?php for($i=1;$i<=$row["item_quantity"];$i++) { ?>
<option value="<?php echo $i ?>"><?php echo $i ?></option>
<?php } ?>
</select>

HTML select option set selected default echo get value php

I have a simple HTML form with a simple select like this
<select name="myselect" selected="<?php echo $_GET['brand'];?>">
<option value="" <?php if($brand== "") echo "selected"; ?>>all brands</option>
<option value="samsung" <?php if($brand== "samsung") echo "selected"; ?>>Samsung</option>
<option value="motorola" <?php if($brand== "motorola") echo "selected"; ?>>Motorola</option>
</select>
What I am trying to do is because its a search filtering results form if the user choose Samsung as default brand to search next page with filteres search results will the select option default selected Samsung and no other. If user select to search Motorola then the selected option default will be Motorola.
How do I fix this?
selected is attribute of option not select, so remove it from select tag, change to:
<?php $brand = trim( strtolower($_GET['brand']) ); ?>
<select name="myselect">
<option value="" <?php if($brand== "") echo "selected"; ?>>all brands</option>
<option value="samsung" <?php if($brand== "samsung") echo "selected"; ?>>Samsung</option>
<option value="motorola" <?php if($brand== "motorola") echo "selected"; ?>>Motorola</option>
</select>
This is Simple Example of selected=selected by using foreach loop and ternary operators in php... use can easily understand and customize that code...
<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $key => $value) { ?>
<option value="<?php echo $key;?>" <?php echo ($key == '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>
<?php $selected_brand = $_GET['brand'];
$temp_str = '';
$temp_str .= '<select name="myselect">';
$brands_array = array("all" => "all brands", "samsung" => "Samsung", "motorola" => "Motorola");
foreach ($brands_array as $key => $value) {
if($key == $selected_brand){
// For selected option.
$temp_str .= '<option value="'.$key.'" selected>'.$value.'</option>';
} else {
$temp_str .= '<option value="'.$key.'">'.$value.'</option>';
}
}
$temp_str .= '</select>';
echo $temp_str; // Select box.
?>

PHP with dropdown selection

I have list of items in my dropdown. Now I wish to select item according to database value. Suppose I have list of cities their are nearly 300 cities. I have city value as new jersey in my record. Now while editing form checking each options is not possible for 300 options. Like
<option value="A" <? if ($a="A") echo "selected"; ?> >A</option>
<option value="B" <? if ($a="B") echo "selected"; ?> >B</option>
<option value="C" <? if ($a="C") echo "selected"; ?> >C</option>
<option value="D" <? if ($a="D") echo "selected"; ?> >D</option>
<option value="E" <? if ($a="E") echo "selected"; ?> >E</option>
<option value="F" <? if ($a="F") echo "selected"; ?> >F</option>
<option value="G" <? if ($a="G") echo "selected"; ?> >G</option>
<option value="H" <? if ($a="H") echo "selected"; ?> >H</option>
Isn't any way to minimise for 300 records. Can't I write short code for this?
** NOTE My options values are not stored in array.**
suppose your values are stored in an array called $options, you could write something like this:
foreach($options as $option)
{
echo "<option value=\"$option\"";
if($option == $a)
{
echo ' selected="selected"';
}
echo ">$option</option>";
}
you should use loops for output
like
$result = mysql_query('select id, city from cities');
while($row = mysql_fetch_assoc($result)) {
echo '<option value=' . $row['id'] . (($row['city'] == 'new jersey') ? 'selected' : '') . " >" . $row['city'] . '</option>';
}
Try range function in php:
<?php foreach (range('A', 'Z') as $letter){?>
<option value="<?php echo $letter?>" <? if ($a==$letter) echo "selected='selected'"; ?> ><?php echo $letter?></option>
<?php }?>
Change the range accordingly. You could use this function with integers too.

display from database to dropdown list

I have stored value from drop down list to database. I want to echo the same value to be displayed in that drop down list in my edit form. how can I achieve that in php?
Region
<select name="stf_region">
<option>Select</option>
<option value="1">MDU</option>
<option value="2">TMM</option>
</select>
i have stored in database using value of selection
but i dont know to display that value in same drop down
Use something like this:
<?
$sql = "SELECT id, description FROM dropDownTable";
$rs = mysql_query($sql);
?>
<select name="dropDown">
<option value="-1">Please select...</option>
<? while ($obj = mysql_fetch_object($rs)) { ?>
<option value="<?= $obj->id; ?>" <? if ($data['downDown'] == $obj->id) echo "SELECTED"; ?>>
<?= $obj->description; ?>
</option>
<? } ?>
</select>
Please note $data needs to be set as an associative array containing attributes of the entity that is being edited. This code is flexible because in the case of a form where a user may have submitted an incomplete form $data could be set to the $_POST variable and so all entered fields can be included without the user needing to re-specify fields they previously filled in. This basically means your form template, inserting an entry and editing an entry can be the same!
Well you could do like this
$query = "select id, label from lookup_table";
$result = mysql_query($query);
$html = "<select name='yourname'><option value="">Please select...</option>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$html .= "<option value='$row[id]'>$row[label]</option>";
}
$html = "</select>";
echo ($html);//Display the select in the page
If you're able to get db data into array, you can work with them like this:
<?php
$options = array('label 1' => 'value 1', 'label 2' => 'value 2');
echo "<select name=somename>";
foreach($options as $key => $value){
echo "<option value=" . $value . ">" . $key . "</option>";
}
echo "</select>";
?>
i used the COOKIE to match the value that should be selected when it comes to edit the form.
<?php
while($result_row=mysql_fetch_array($result)){
if ( $_COOKIE['MY_COOKIE'] == $result_row[importance_level_id )
{
echo "<option SELECTED=\"SELECTED\" value=$result_row[importance_level_id]>$result_row[importance_level]</option>";
}
else
{
echo "<option value=$result_row[importance_level_id]>$result_row[importance_level]</option>";
}
?>
Assuming you are ok with selecting the value out of the database into a PHP variable (let's say $region) I think you are just after
Region
<select name="stf_region">
<option>Select</option>
<option value="1"<?php echo ($region == '1') ? ' selected="selected"' : ''; ?>>MDU</option>
<option value="2"<?php echo ($region == '2') ? ' selected="selected"' : ''; ?>>TMM</option>
</select>
This is the most concise answer to the question that I think you are asking. However this is a very specific answer and assumes that your dropdown values are hard-coded and won't really be changing.
If you want a more flexible setup that retrieves the values of the dropdown from the database you are looking for something more along the lines of what has been suggested by Gordon Murray Dent above
<div class="form-group has-success col-md-6">
<label class="control-label" for="state-success">Select Buyer</label>
<select id="state-success" class="form-control ">
<?php
$sql="SELECT full_name FROM `new_customer`";
$data=mysqli_query($dbcon,$sql);
?>
<option>Select byer...</option>
<?php while($row1=mysqli_fetch_array($data)){?>
<option value="<?php echo $row1['full_name'];?>"><?php echo $row1['full_name'];?></option>
<?php } ?>
</select>

Categories