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.
?>
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 am using chosen select drop down to show auto complete drop down. I want to set selected value for edit. I tried following code which works for normal select option but not working for chosen select
<select class="chosen-select" >
<option value=""></option>
<?php if(!empty($list))
{
foreach($list as $d)
{
?>
<option value="<?php echo $d->id; ?><?php if($d->id == 2) { echo "selected"; } ?>"><?php echo $d->name; ?></option>
<?php } } ?>
</select>
You are putting your selected inside your value attribute, you need to write it after :
<select class="chosen-select" >
<option value=""></option>
<?php if(!empty($list)) {
foreach($list as $d) {
?>
<option value="<?php echo $d->id; ?>"<?php if($d->id == 2) { echo " selected"; } ?>><?php echo $d->name; ?></option>
<?php } } ?>
</select>
Building on #roberto06's answer, the following should be a bit cleaner to look at.
BTW, you really should consider using a template engine.
<select class="chosen-select">
<option value=""></option>
<?php if (!empty($list)): ?>
<?php foreach ($list as $d): ?>
<option value="<?php echo $d->id; ?>" <?php echo ($d->id == 2) ? "selected" : "">
<?php echo $d->name; ?>
</option>
<?php endforeach; ?>
<?php endif; ?>
</select>
This always selected the last record from my database.
This is my select tag:
<select name="t_proyek_kd_proyek" id="t_proyek_kd_proyek" class="select-search" />
<option value=""></option>
<?php
$t_cost=$this->db->query("select * from t_proyek ");
foreach($t_cost->result() as $value){
$selected= '';
if($t_proyek_kd_proyek == $value->nm_proyek){
$selected = 'selected';
}
?>
<option value="<?php echo $value->kd_proyek; ?>" echo ' selected="selected"'; >
<?php echo $value->nm_proyek; ?>
</option>
<?php }?>
</select>
And this is my controller:
$row = $this->T_cost_model->get_by_id($id);
if ($row) {
$data = array(
'button' => 'Update',
'action' => site_url('konsultan/cost/update_action'),
'kd_cost' => set_value('kd_cost', $row->kd_cost),
'investasi_awal' =>rupiah(set_value ('investasi_awal', $row->investasi_awal)),
'b_operasional' => rupiah(set_value('b_operasional', $row->b_operasional)),
'g_cost' => rupiah(set_value('g_cost', $row->g_cost)),
'disbenfit' => rupiah(set_value('disbenfit', $row->disbenfit)),
'pwc' => set_value('pwc', $row->pwc),
't_proyek_kd_proyek' => set_value('t_proyek_kd_proyek', $row->t_proyek_kd_proyek),
);
$this->load->view('konsultan/t_cost_form', $data);
In your HTML, your last option tag has selected="selected" explicitly set:
option value="<?php echo $value->kd_proyek; ?>" <?php echo 'selected="selected"'; ?>
Wrap that in a condition and the selected option from your loop should work.
option value="<?php echo $value->kd_proyek; ?>" <?php if ($selected) echo 'selected="selected"'; ?>
change your <select> html code value like this
<select name="t_proyek_kd_proyek" id="t_proyek_kd_proyek" class="select-search" />
<option value=""></option>
foreach($t_cost->result() as $value){
$selected= '';
if($t_proyek_kd_proyek == $value->nm_proyek){
$selected = ' selected="selected" ';
}
?>
<option value="<?php echo $value->kd_proyek; ?>" <?= $selected?> >
<?php echo $value->nm_proyek; ?>
</option>
<?php }?>
</select>
hope it will help
I need to get selected value from db into select box. please, tell me how to do it. Here is the code.
Note: 'options' value depends on the category.
<?php
$sql = "select * from mine where username = '$user' ";
$res = mysql_query($sql);
while($list = mysql_fetch_assoc($res)){
$category = $list['category'];
$username = $list['username'];
$options = $list['options'];
?>
<input type="text" name="category" value="<?php echo '$category' ?>" readonly="readonly" />
<select name="course">
<option value="0">Please Select Option</option>
<option value="PHP">PHP</option>
<option value="ASP">ASP</option>
</select>
<?php
}
?>
I think you are looking for below code changes:
<select name="course">
<option value="0">Please Select Option</option>
<option value="PHP" <?php if($options=="PHP") echo 'selected="selected"'; ?> >PHP</option>
<option value="ASP" <?php if($options=="ASP") echo 'selected="selected"'; ?> >ASP</option>
</select>
The easiest way I can think of is the following:
<?php
$selection = array('PHP', 'ASP');
echo '<select>
<option value="0">Please Select Option</option>';
foreach ($selection as $selection) {
$selected = ($options == $selection) ? "selected" : "";
echo '<option '.$selected.' value="'.$selection.'">'.$selection.'</option>';
}
echo '</select>';
The code basically places all of your options in an array which are called upon in the foreach loop. The loop checks to see if your $options variable matches the current selection it's on, if it's a match then $selected will = selected, if not then it is set as blank. Finally the option tag is returned containing the selection from the array and if that particular selection is equal to your $options variable, it's set as the selected option.
for example ..and please use mysqli() next time because mysql() is deprecated.
<?php
$select="select * from tbl_assign where id='".$_GET['uid']."'";
$q=mysql_query($select) or die($select);
$row=mysql_fetch_array($q);
?>
<select name="sclient" id="sclient" class="reginput"/>
<option value="">Select Client</option>
<?php $s="select * from tbl_new_user where type='client'";
$q=mysql_query($s) or die($s);
while($rw=mysql_fetch_array($q))
{ ?>
<option value="<?php echo $rw['login_name']; ?>"<?php if($row['clientname']==$rw['login_name']) echo 'selected="selected"'; ?>><?php echo $rw['login_name']; ?></option>
<?php } ?>
</select>
Just Add an extra hidden option and print selected value from database
<option value="<?php echo $options;?>" hidden><?php echo $options;?></option>
<option value="PHP">PHP</option>
<option value="ASP">ASP</option>
Select value from drop down.
<select class="form-control" name="category" id="sel1">
<?php foreach($data as $key =>$value) { ?>
<option value="<?php echo $data[$key]->name; ?>"<?php if($id_name[0]->p_name==$data[$key]->name) echo 'selected="selected"'; ?>><?php echo $data[$key]->name; ?></option>
<?php } ?>
</select>
THE EASIEST SOLUTION
It will add an extra in your options but your problem will be solved.
<?php
if ($editing == Yes) {
echo "<option value=\".$MyValue.\" SELECTED>".$MyValue."</option>";
}
?>
$option = $result['semester'];
<option >Select</option>
<option value="1st" <?php if($option == "1st") echo 'selected = "selected"'; ?>>1st</option>
<option value="2nd" <?php if($option == "2nd") echo 'selected = "selected"'; ?>>2nd</option>
<option value="3rd" <?php if($option == "3rd") echo 'selected = "selected"'; ?>>3rd</option>
<option value="4th" <?php if($option == "4th") echo 'selected = "selected"'; ?>>4th</option>
<option value="5th" <?php if($option == "5th") echo 'selected = "selected"'; ?>>5th</option>
<option value="6th" <?php if($option == "6th") echo 'selected = "selected"'; ?>>6th</option>
<option value="7th" <?php if($option == "7th") echo 'selected = "selected"'; ?>>7th</option>
<option value="8th" <?php if($option == "8th") echo 'selected = "selected"'; ?>>8th</option>
</select>
BEST code and simple
<select id="example-getting-started" multiple="multiple" name="category">
<?php
$query = "select * from mine";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results)){
?>
<option value="<?php echo $rows['category'];?>"><?php echo $rows['category'];?></option>
<?php
}
?>
</select>
You can also do like this ....
<?php $countryname = $all_meta_for_user['country']; ?>
<select id="mycountry" name="country" class="user">
<?php $myrows = $wpdb->get_results( "SELECT * FROM wp_countries order by country_name" );
foreach($myrows as $rows){
if( $countryname == $rows->id ){
echo "<option selected = 'selected' value='".$rows->id."'>".$rows->country_name."</option>";
} else{
echo "<option value='".$rows->id."'>".$rows->country_name."</option>";
}
}
?>
</select>
Answer is simple.
when u pass value from dropdown.
Just use as if else.
for eg:
foreach($result as $row) {
$GLOBALS['output'] .='<option value="'.$row["dropdownid"].'"'.
($GLOBALS['passselectedvalueid']==$row["dropwdownid"] ? ' Selected' : '').'
>'.$row['valueetc'].'</option>';
}
<?php
$sql = "select * from mine where username = '$user' ";
$res = mysql_query($sql);
while($list = mysql_fetch_assoc($res)){
$category = $list['category'];
$username = $list['username'];
$options = $list['options'];
?>
<input type="text" name="category" value="<?php echo '$category' ?>" readonly="readonly" />
<select name="course">
<option value="0">Please Select Option</option>
<option value="PHP" <?php echo $options == 'PHP' ? 'selected' : ''; ?> >PHP</option>
<option value="ASP" <?php echo $options == 'ASP' ? 'selected' : ''; ?> >ASP</option>
</select>
<?php
}
?>
USING PDO
<?php
$username = "root";
$password = "";
$db = "db_name";
$dns = "mysql:host=localhost;dbname=$db;charset=utf8mb4";
$conn = new PDO($dns,$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "select * from mine where username = ? ";
$stmt1 = $conn->prepare($sql);
$stmt1->execute(array($_POST['user']));
$all = $stmt1->fetchAll(); ?>
<div class="controls">
<select data-rel="chosen" name="degree_id" id="selectError">
<?php
foreach($all as $nt) {
echo "<option value =$nt[id]>$nt[name]</option>";
}
?>
</select>
</div>
I'm using eval() PHP function like this:
My PHP code:
$selOps1 = $selOps2 = $selOps3 = '';
eval('$selOps'. $dbRow["DBitem"] . ' = "selected";');
Then in my select box I use it like this:
<select>
<option <?=$selOps1?> value="1">big</option>
<option <?=$selOps2?> value="2">Middle</option>
<option <?=$selOps3?> value="3">Small</option>
</select>
Put value from db into a variable and check like following code example
<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>
This may help you.
?php
$sql = "select * from mine where username = '$user' ";
$res = mysql_query($sql);
while($list = mysql_fetch_assoc($res))
{
$category = $list['category'];
$username = $list['username'];
$options = $list['options'];
?>
<input type="text" name="category" value="<?php echo '$category' ?>" readonly="readonly" />
<select name="course">
<option value="0">Please Select Option</option>
// Assuming $list['options'] is a coma seperated options string
$arr=explode(",",$list['options']);
<?php foreach ($arr as $value) { ?>
<option value="<?php echo $value; ?>"><?php echo $value; ?></option>
<?php } >
</select>
<?php
}
?>
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.