Set default option in select-element using php - php

I'm looking for a simple way to dynamically change the default item in a select-element without adding a ton of code into every option-element.
This is an example of a select-element that allows you to select a month and it always sets the current month as the default item:
<select name="month">
<option <?php echo ((date("n")==1)?'selected="selected"':'')?> value="1">Januar</option>
<option <?php echo ((date("n")==2)?'selected="selected"':'')?> value="2">Februar</option>
<option <?php echo ((date("n")==3)?'selected="selected"':'')?> value="3">März</option>
<option <?php echo ((date("n")==4)?'selected="selected"':'')?> value="4">April</option>
<option <?php echo ((date("n")==5)?'selected="selected"':'')?> value="5">Mai</option>
<option <?php echo ((date("n")==6)?'selected="selected"':'')?> value="6">Juni</option>
<option <?php echo ((date("n")==7)?'selected="selected"':'')?> value="7">Juli</option>
<option <?php echo ((date("n")==8)?'selected="selected"':'')?> value="8">August</option>
<option <?php echo ((date("n")==9)?'selected="selected"':'')?> value="9">September</option>
<option <?php echo ((date("n")==10)?'selected="selected"':'')?> value="10">Oktober</option>
<option <?php echo ((date("n")==11)?'selected="selected"':'')?> value="11">November</option>
<option <?php echo ((date("n")==12)?'selected="selected"':'')?> value="12">Dezember</option>
</select>
As you can see, there is just way too much code in it.
I'm wondering if anyone of you has a better idea on how to do this.

Use a loop:
<?php
$months = [
1=>'January',
2=>'february',
3=>'march'
....//etc
];
?>
<select name="month">
<?php foreach($months as $key=>$month):?>
<option <?= ((date("n")==$key)?'selected="selected"':'')?> value="<?= $key;?>"><?= $month;?></option>
<?php endforeach;?>
</select>

You could create an array of months and then check it like that.
<?php
$months = array(
array(
"monthNumber" => 1,
"name" => "January"
),
array(
"monthNumber" => 2,
"name" => "Feb"
),
array(
"monthNumber" => 3,
"name" => "March"
)
);
?>
<select name="month">
<?php
foreach ($months as $month) {
echo "<option " . ((date("n") == $month['monthNumber']) ? 'selected="selected"' : ''). ">".$month['name']."</option>";
}
?>
</select>

Use foreach loop
<?php
$months=array('1'=>'January','2'=>'Febuary','3'=>'March',4=>'April','5'=>'May','6'=>'June','7'=>'July','8'=>'August','9'=>'September',10=>'October','11'=>'November','12'=>'December');
?>
<select name='month'>
<?php foreach($months as $num=>$month) {?>
<option <?php echo ((date("n")==$num)?'selected="selected"':'')?>value="<?php echo $num;?>"><?php echo $month; ?>
</option>
</select>
It may be helpful..

Related

PHP: html select in form doesn't display value from array with for each

I have this array with a list of countries.
$country_list = array(
"Afghanistan",
"Albania",
"Algeria",
"Andorra",
"Angola"
};
I show these countries with a select in my form
<select name="countries">
<option value=""></option>
<?php foreach($country_list as $key => $value): ?>
<option value="<?php $key ?>"><?php $value ?></option>
<?php endforeach ?>
</select><br>
For some reason the value is showing up as an empty string in my select.
You forgot to write echo
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
If you use php, use "echo" to display a value:
<select name="countries">
<option value=""></option>
<?php foreach($country_list as $key => $value): ?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php endforeach ?>
</select><br>

Pre populating selectbox using php

I have an issue for which I am not able to think of a solution.
I have an array of data which I get from the server. I have to pre populate a form which already have some values.
<select id="select1" name="Salutation" class="field-size-top-large" >
<option value="">-- please select -- </option>
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
</select>
I am getting an array
array(11) {
[0]=> string(4) "Ms."
[1]=> string(8) "Y"
}
I have to check if [0]=>'Ms.' is there in select list, if there it should be selected else default is selected. Any ideas?
use this
$options = array('Mr.', 'Ms.');
$data = array(0 => 'Ms.', 1 => 'Y');
<select id="select1" name="Salutation" class="field-size-top-large">
<option value="">-- please select --</option>
<?php foreach ($options as $option): ?>
<option value="<?php echo $option?>" <?php echo $option == $data[0] ? 'selected' : ''; ?>><?php echo $option; ?></option>
<?php endforeach; ?>
</select>
Try this:
$options = ['Mr.', 'Ms.']; // the default options
$data = [0 => 'Ms.', 1 => 'Y']; // data from server
<select id="select1" name="Salutation" class="field-size-top-large">
<option value="">-- please select --</option>
<?php foreach ($options as $option): ?>
<option value="<?php echo $option; ?>" <?php echo in_array($option, $data) ? 'selected' : ''; ?>><?php echo $option; ?></option>
<?php endforeach; ?>
</select>
My soultion:
the data array I am getting from the server i.e 0=>'Ms.' is the only value I can check for the rest are different fields
<select id="select1" name="Salutation" class="field-size-top-large" >
<option value="">-- please select --</option>
<option value="Mr." <?php echo 'Mr.'== $data[0]? 'selected':''?>> Mr. </option>
<option value="Ms."<?php echo 'Ms.'== $data[0]? 'selected':''?>>Ms.</option>
</select>

How To Call Array from other File

i have a array from oher file php and show in select data html
this is my array
array.php
<?php
$category_attachment = array( "SPK" ,
"Justifikasi" ,
"PR" ,
"RAB" ,
"Proc" ,
"PO" ,
"Notulen" ,
"Sertifikat" ,
"BAUT" ,
"BAST" ,
"Tagihan" ,
"Other"
); ?>
and this myfile.php
<?php include "array.php" ?>
<select name="category" id="category">
<option value="">Choose Category</option>
// I want array data in here
</select>
Help Me Thank's
Try this
<select name="category" id="category">
<option value="">Choose Category</option>
<?php
foreach ($category_attachment as $value) {
?>
<option value="<?php echo $value ?>"><?php echo $value ?></option>
<?php
}
?>
</select>
just try print_r($category_attachment); in your myfile.php and see what happens. you should be able to access the variable after you included the file
Also, you should disable the first option by using the disabled attribute ;)
<?php
include "array.php"
print_r($category_attacment);
?>
<select name="category" id="category">
<option disabled>Choose Category</option>
<?php
foreach($category_attachment as $cat) {
echo "<option value='" . $cat . "'>" . $cat . "</option>";
}
?>
</select>
This example won't work:
<?php
print_r($category_attacment);
include "array.php"
?>
you have to include the file before you can access the variable.
You could do the following :
<select name="category" id="category">
<option value="">Choose Category</option>
<?php
foreach($category_attachment as $category){
echo '<option value="'.$category'">'.$category.'</option>';
}
?>
</select>
Give a look at foreach doc, which is very useful when using array :
http://php.net/manual/en/control-structures.foreach.php
You can do this:
<?php include "array.php" ?>
<select name="category" id="category">
<option value="">Choose Category</option>
<?php foreach ($category_attachment as $category) {?>
<option value="<?php echo $category; ?>"><?php echo $category; ?></option>
<?php } ?>
</select>
As simple as this,
<select name="category" id="category">
<?php
foreach ($category_attachment as $value) {
?>
<option value="<?= $value ?>"><?= $value ?></option>
<?php
}
?>
</select>

How to make dropdown option selected against a variable in php

I have a dropdown like the following.
<select>
<option value="Mr">Mr</option>
<option value="Dr">Dr</option>
<option value="Prof">Prof</option>
</select>
I am getting a value from data base in $selected_value variable. Based on this value I want to make one option from the above select to be selected.
Eg: If $selected_value = Mr, <option value="Mr" selected>Mr</option>
if $selected_value = Dr, <option value="Dr" selected>Dr</option>
update:
now when i am inspecting element i am getting like below.but not selecting Dr.but it is orking in w3schools try editor.
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected="selected">Dr</option>
<option value="Prof">Prof</option>
</select>
update 2
see screen shot:
update3
now it works! added name for <select>
This will work for you problem
try this code
<select>
<option value="Mr" <?=($selected_value=="Mr") ? "selected" : ""?>>Mr</option>
<option value="Dr" <?=($selected_value=="Dr") ? "selected" : ""?>>Dr</option>
</select>
try this..
<option value="Mr" <?php if($selected_value == 'Mr') echo 'selected' ?>>Mr</option>
<option value="Dr" <?php if($selected_value == 'Dr') echo 'selected' ?>>Dr</option>
<option value="Prof" <?php if($selected_value == 'Prof') echo 'selected' ?>>Prof</option>
Or you can use by using jquery
<script>
$('select option[value="<?php echo $selected_value ?>"]').attr('selected','true')
</script>
As per your current HTML use the code below:
<select name="your_select_name">
<option <?php echo (($selected_value=="Mr")?"selected":"") ?> value="Mr">Mr</option>
<option <?php echo (($selected_value=="Dr")?"selected":"") ?> value="Mr">Dr</option>
<option <?php echo (($selected_value=="Prof")?"selected":"") ?> value="Mr">Prof</option>
</select>
If the value of this variable($selected_value) returns "Dr" then 2nd option will be selected. And also give a name of your select tag.
I changed my solution so it fits yours I hope.
UPDATE:
<select name="dropdownlist">
<?
$options = array("Mr", "Dr", "Prof");
foreach($options as $option){
if($_POST['dropdownlist'] == $option){
echo '<option selected="selected">' .$option. '</option>';
}else{
echo '<option>' .$option. '</option>';
}
}
?>
</select>
If you also have an array of your options you could create the option tags by looping through each one of them. In that loop you then can check if the $selected_value matches $option_value like so:
<select>
<?php foreach($options as $option_value => $option_displayName) : ?>
<option
value="<?php echo $option_value; ?>"
<?php echo $option_value == $selected_value ? 'selected' : ''; ?>>
<?php echo $option_displayName; ?>
</option>
<?php endforeach; ?>
</select>
To do what you want you'd have to build the select dynamically like the following example:
<?php
$selects = array(
array('name' => 'Mr', 'value' => 'Mr'),
array('name' => 'Dr', 'value' => 'Dr'),
array('name' => 'Prof', 'value' => 'Prof'),
);
$selected_option = 'Dr';
echo '<select>';
foreach($selects as $select) {
if($select['value'] == $selected_option) {
echo '<option value="'.$select['value'].'" selected>' .$select['name']. '</option>';
} else {
echo '<option value="'.$select['value'].'">' .$select['name']. '</option>';
}
}
echo '</select>';
?>
Which outputs:
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected>Dr</option>
<option value="Prof">Prof</option>
</select>
Example
Try as follows .
<select name="select_options">
<option value="Mr">Mr</option>
<option value="Dr">Dr</option>
<option value="Prof">Prof</option>
</select>
After hit submit button. Then you will get value in $_POST['select_options']
There are many ways to achieve what you're doing. I can think of two straight ways to do this.
The first is ugly:
Insert in each option a php tag and check if value is selected:
<select>
<option <?php if ($selected_value == 'Mr') echo 'selected'; ?> value="Mr">Mr</option>
<option <?php if ($selected_value == 'Dr') echo 'selected'; ?> value="Dr">Dr</option>
<option <?php if ($selected_value == 'Prof') echo 'selected'; ?> value="Prof">Prof</option>
</select>
Otherwise, I would personally write a little helper
function generateSelect(array $entries, $selected)
{
$ret = '<select>'
foreach ($entries as $entry) {
$ret .= '<option';
if ($entry == $selected) {
$ret .= ' selected';
}
$ret .= ' value="'.$entry.'"';
$ret .= '>'.$entry.'</option'>;
}
return $ret;
}
It is just an example and its functionality could be expanded. It SHOULD work, but I haven't tried it myself (wrote it quickly)
You have mistaken syntax
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected="selected">Dr</option>
<option value="Prof">Prof</option>
</select>
this will work
<select>
<option value="Mr">Mr</option>
<option value="Dr" selected>Dr</option>
<option value="Prof">Prof</option>
</select>

PHP Dropdown Validation

This is the part of an edit page in PHP
Here I am displaying the country which is already selected by the user and this code works fine.
And in this case there are3 countries only.
If I have a lot of countries, then I have to validate with each country and the no: of lines of code will increase.
Is there any other option to acheive this?
Select Country:
<select name="country">
<?php if($country == "india") { ?>
<option value="">-Select Country-</option>
<option value="india" selected>india</option>
<option value="us">us</option>
<option value="uk">uk</option>
<?php } else if($country == "us"){ ?>
<option value="">-Select Country-</option>
<option value="india">india</option>
<option value="us" selected>us</option>
<option value="uk">uk</option>
<?php } else{ ?>
<option value="">-Select Country-</option>
<option value="india">india</option>
<option value="us">us</option>
<option value="uk" selected>uk</option>
<?php } ?>
</select>
load the countries into array
$countries = array("india", "us", "uk");
then,
<select name="country">
<?php
foreach($countries as $c)
{
echo "<option ";
if ($c == $country) echo "selected";
echo ">$c</option>";
}
?>
</select>
is this your update county page then do below
first get the selected country from database let
$row['country']='india';
and your country Array is
$countryArray = array ('india','us','uk');
then do below
<select name="country">
<option value="">-Select Country-</option>
<?php foreach( $countryArray as $country) { ?>
<option value="india" <?php if($row['country']===$country ) { ?> selected ="selected" <? } ?><?php echo $country?></option>
<?php } ?>
</select>
Hm, I believe you would be looking for something like this:
<?php
$selected = "india";
$countries = Array(
["india"] => "India",
["us"] => "United States",
["uk"] => "United Kindom",
);
foreach( $countries as $id => $country ){
echo '<option value="'.$id.'"', $selected == $id ? ' selected' : '' ,'>' . $country . '</option>';
}
?>
Excuse me, I have not coded in PHP in a while, but I believe this is correct.

Categories