How to put a default value in a dropdown in php? - php

My code looks like:
<select autofocus="autofocus" name="SourceCountry" id="SourceCountry">
<?php populate_country();?>
</select>
I am populating all the countries of the world in that dropdown. I want a particular country name(say Japan) as default selected. I am not sure which attribute or property of the select tag does this. Tried to use many, but didnt work out. Can anyone suggest?
The code of populate_country goes like this:
if(connect_to_DB()==1)
$result=FetchCountriesList();
//mysqli_data_seek($result,0);
while($row = mysqli_fetch_assoc($result))
{
echo '<option value='.$row['CountryName'].'>'.$row['CountryName'].'</option>';
}
In FetchCountriesList(), there is a select query like:
SELECT distinct CountryName from Countries
Thanks

Edit your function and try to find Japan and set this one as Selected :)
if(connect_to_DB()==1) $result=FetchCountriesList();
//mysqli_data_seek($result,0);
while($row = mysqli_fetch_assoc($result)) {
if($row['CountryName'] !== "Japan") {
echo '<option value='.$row['CountryName'].'>'.$row['CountryName'].'</option>';
} else {
echo '<option value='.$row['CountryName'].' selected="selected">'.$row['CountryName'].'</option>';
}
}

Add attribute selected. Try this:
<select name="country">
<option value="kor">Korea</option>
<option value="rus">Russia</option>
<option selected="selected" value="jap">Japan</option>
</select>

Add selected for your option in your function populate_country(). (in the option you want to select as default only)

Add the seleteced attribute, e.g.:
<option value="test" selected="selected">Bla</option>
$defValue = 'Japan';
while($row = mysqli_fetch_assoc($result)) {
echo '<option value="' . $row['CountryName'] . '"';
if ($row['CountryName'] === $defValue) {
echo ' selected="selected"';
}
echo '>';
echo $row['CountryName'] . '</option>';
}

Just add attribute selected="selected" on the option value that you wish to be selected.
E.g.:
<option value="Japan" selected="selected">Japan</option>
To use this in your function, replace your function with this:
function populate_country($selected = NULL) {
if(connect_to_DB()==1) $result=FetchCountriesList();
//mysqli_data_seek($result,0);
while($row = mysqli_fetch_assoc($result)) {
echo '<option value="'.$row['CountryName'].'" '.($selected == $row['CountryName'] ? 'selected="selected"' : NULL).'>'.$row['CountryName'].'</option>';
}
}
You can then use this in your HTML:
<select autofocus="autofocus" name="SourceCountry" id="SourceCountry">
<?php populate_country("Japan");?>
</select>

<select>
<option> Red </option>
<option selected="selected"> blue </option>
<option> yellow </option>
</select>
Blue would be the selected in that dropdown.
Basically you need to loop throught your values and match if the value you want matches with the ones you have, and add the selected="selected" string to that option:
I would do something like this: (untested)
function populate_country($country){
$countries = array('algeria', 'japan', 'mexico', 'united kingdom' ..... );
foreach($countries as $country){
$selected = (strtolower($selected) == $country) ? ' selected="selected"' : null;
echo "<option$selected>".ucwords($country)."</option>\r\n";
}
}

Related

how dynamic dropdown set select use

am doing like this. this is my dynamic dropdown which is populating from database result. when i submit the form, validation apply, if validation error occur on empty field, form stops to submit. BUT all dropdown also removes its values, so i again fill all form instead of empty fields
my previous code is: before apply set select
<select name="position_filled_against_id" id="position_filled_against_id">
<option value="">Select</option>
<?php
foreach($position_filled_against as $position_filled)
{
$selected = "";
echo '<option value="'.$position_filled->position_filled_against_id.'" >'.$position_filled->code.'-'.$position_filled->name.'</option>';
}
?>
</select>
after apply set select: but syntax error
<select name="position_filled_against_id" id="position_filled_against_id"><option value="">Select</option>
<?php
foreach($position_filled_against as $position_filled)
{
$selected = "";
echo '<option value="'.set_select("position_filled_against_id",$position_filled->position_filled_against_id,TRUE).'" >'.$position_filled->code.'-'.$position_filled->name.'</option>';
}
?>
</select>
You can try with below code it will help you
<select name="position_filled_against_id" id="position_filled_against_id">
<option value="">Select</option>
<?php
foreach($position_filled_against as $position_filled)
{
$selected = "";
if($_REQUEST['position_filled_against_id']==$position_filled->position_filled_against_id)
{
$selected = 'selected="selected"';
}
echo '<option value="'.$position_filled->position_filled_against_id.'" '.$selected.' >'.$position_filled->code.'-'.$position_filled->name.'</option>';
}
?>
</select>
i remove the syntax error
<select name="position_filled_against_id" id="position_filled_against_id">
<option value="">Select</option>
<?php
foreach($position_filled_against as $position_filled)
{
$selected = "";
echo '<option value="'.$position_filled->position_filled_against_id.'" '.set_select("position_filled_against_id","$position_filled->position_filled_against_id", TRUE).' >'.$position_filled->code.'-'.$position_filled->name.'</option>';
}
?>
</select>

isset($_POST['tag-name']) is set but $_POST['tag-name'] return empty when selecting dynamic list

I has created dynamic list in php.
<select name="student" >
<option selected disable class="hideoption">Student Name</option>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo<option value='".$row['path']."'>'".$row['studentName']."'</option>";
}
?>
</select>
When I'm selected the list it give empty string. But when I'm not selected anything it return the first value which is Student Name. I tried to get the value from this line.
if(isset($_POST['student'])){
$selectedName = $_POST['student'];
}
I also try to checked whether the isset is set or empty. The isset is set but its empty.
This is the only solution Google provided.Ideas?
Edit
I have solved the problem. The explanation on the answer below.
At first I thought $_POST['student'] returning the text inside the <option> tag and I was wrong. I learnt that it return the value which is should be set in <option> attribute, So I just set the value to $row['studentName'], because $row['path'] returned empty string. Correct me if what I said is wrong. So basically, the code looks like below.
<select name="student" >
<option selected disable class="hideoption">Student Name</option>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo<option value='".$row['studentName']."'>'".$row['studentName']."'</option>";
}
?>
</select>
Thanks for all your responses. Your responses made me think what should I do.
Use below code:
<select name="student" id="student" >
<option selected disable class="hideoption">Student Name</option>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
echo "<option name='".$row['studentName']."' value='".$row['path']."'>'".$row['studentName']."'</option>";
}?>
</select>
You should be use this line isset($_POST['studentName']) && $selected = $_POST['studentName'] == $row['studentName'] ? 'selected = "selected"' : null; for selected option
<select name="student" >
<option selected disable class="hideoption">Student Name</option>
<?php
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
$selected = isset($_POST['studentName']) && $_POST['studentName'] == $row['studentName'] ? 'selected = "selected"' : null;
echo "<option ".$selected." value='".$row['path']."'>".$row['studentName']."</option>";
}
?>
</select>
#dongcheng This is the same code but with better alignments. So you can see your code clearly.
<select name="student">
<option selected disable class="hideoption">Student Name</option>
<?php
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
echo '<option value="' . $row['path'] . '">' . $row['studentName'] . '</option>';
}
?>
</select>
use
$selectedStudent = !empty($_POST['student']) ? $_POST['student'] : '';
if ($selectedStudent) {
// your code
}

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 show the selected item name in the drop down list?

I have created a drop down list which is working perfectly fine, its fetching data from database and showing it in the drop-down list. The problem is that I am unable to identify that where to use 'selected'attribute in the select tag. Right now whatever the field I select it opens it, but in the drop down list it shows the first given name. I also tried to use 'selected' attribute, but it was showing the last item name in the drop-down list.
Kindly check it and guide me how to use 'selected' attribute in the loop.
<?php
//Drop Down List
$sub_query = "select * from sub_categories where category_id=$category_id ";
if (!$sub_query_run = mysql_query($sub_query))
{
echo mysql_error();
}
else
{
echo "<select name='menu1' id='menu1' >
<option value='#'> All</option> ";
while ($sub_query_fetch = mysql_fetch_array($sub_query_run))
{
//$sub_query_fetch = mysql_fetch_array($sub_query_run);
$sub_category_id2 = $sub_query_fetch['sub_category_id'];
$sub_category_name = $sub_query_fetch['sub_category_name'];
echo "<option value='earings2.php?sub_category_id=$sub_category_id2' >"
.htmlspecialchars($sub_category_name= $sub_query_fetch['sub_category_name']).
"</option>";
}
}
follow this example..
<select name="cate" id="cate" class="reginput" >
<option value="">Select Category</option>
<?php $s2="select * from tbl_category order by cate_name";
$q2=mysql_query($s2);
while($rw2=mysql_fetch_array($q2)) {
?>
<option value="<?php echo $rw2['id']; ?>"<?php if($rw2['id']==$row['cate_id']) echo 'selected="selected"'; ?>><?php echo $rw2['cate_name']; ?></option><?php } ?>
</select>
You have to add a condition for the selected item.
echo "<option value='earings2.php?sub_category_id=$sub_category_id2'";
if ($sub_category_id2 == $MATCHING_CATEGORY_ID) echo " selected";
echo ">".htmlspecialchars($sub_category_name= $sub_query_fetch['sub_category_name'])."</option>";
Where $MATCHING_CATEGORY_ID is the category id that will be selected.
<option value="#" selected>ALL</option>
"selected" should be included in option tag
Try it like,
// get the category id from request parameter
$sc_id=isset($_REQUEST['sub_category_id']) ? $_REQUEST['sub_category_id'] : "";
while ($sub_query_fetch= mysql_fetch_array($sub_query_run))
{
//$sub_query_fetch= mysql_fetch_array($sub_query_run);
$sub_category_id2= $sub_query_fetch['sub_category_id'];
$sub_category_name= $sub_query_fetch['sub_category_name'];
$sel='';
if($sc_id==$sub_category_id2)// get the selected item
$sel='selected="selected"';
echo "<option value='earings2.php?sub_category_id=$sub_category_id2' ".$sel." >"
.htmlspecialchars($sub_category_name= $sub_query_fetch['sub_category_name']).
"</option>";
}
you need to use select in <option> tag
try this
while ($sub_query_fetch= mysql_fetch_array($sub_query_run))
{
//$sub_query_fetch= mysql_fetch_array($sub_query_run);
$sub_category_id2= $sub_query_fetch['sub_category_id'];
$sub_category_name= $sub_query_fetch['sub_category_name'];
$selected = ($isSelected == $sub_category_id2) ? 'selected' : ''; should be your selected condition fetch from db
echo "<option ".$selected."
value='earings2.php?sub_category_id=$sub_category_id2' >"
.htmlspecialchars($sub_category_name= $sub_query_fetch['sub_category_name']).
"</option>";
}

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