I am doing an dropdown box, where I have let's say we have "option1" and "option2", the dropbox selects(marks) the "option1" and then we select the "option2", I want it to mark the "option2" in the dropdown box, but it doesn't mark it.
I'm trying to avoid to do javascript on this one, so I wonder if I can do it only on PHP.
Advices? Thanks!
Edit.
Well the problem is that i dont know how many options i have before building the dropdown menu. I get an array generated from a table in a database and make the options based on that.
Code:
<select name="department">
<?php foreach(bloggModelControler::getDepartments($_SESSION['user']) as $tempDepartment){
if(strcmp($tempDepartment, $department) == 0){
$selected = ".selected='selected'.";
}else{
$selected = ".selected=''.";
}
$dropdown = "<option \"$selected\" value=\"$tempDepartment\">\"$tempDepartment\" Selected</option>";
echo $dropdown;
}?>
</select>
and $department:
<?php
if(isset($_POST['department'])){
$department = $_POST['department'];
}else{
$departments = bloggModelControler::getDepartments($_SESSION['user']);
$department = $departments[0];
}
?>
Updated answer based on updated question (included code)
Don't put the periods inside the text variables for 'selected'.
if(strcmp($tempDepartment, $department) == 0){
$selected = "selected='selected'";
}else{
$selected = "selected=''";
}
Previous answer
In your PHP code that generates the HTML for the Select box, you have to specify which option is selected.
For example:
<select name="selectbox">
<option <?php if ($_POST['selectbox'] == 'option1') echo 'selected="selected"';?>>option1</option>
<option <?php if ($_POST['selectbox'] == 'option2') echo 'selected="selected"';?>>option2</option>
</selected>
Alternate syntax:
<select name="selectbox">
<option <?= ($_POST['selectbox'] == 'option1')? 'selected="selected"' : '';?>>option1</option>
<option <?= ($_POST['selectbox'] == 'option2')? 'selected="selected"' : '';?>>option2</option>
</selected>
Related
I am trying to list some data after dropdown selection and submit button press. Further I want the selection made to be displayed on the dropdown box even after form submit. The values appearing on the selectbox are coming from mysql dynamically. I have tried something but things are not working out. Any insight will be quite helpful. Following is my code that I am trying,
<select style="width:250px;" name="batch_number" class="form-control" id="user_id" required="">
<option value="">Select Batch number---Org.</option>
<?php
$batch_sql=mysql_query("select batch, batch_next tbl order by date desc");
while ($batch_data=mysql_fetch_array($batch_sql))
{
$batch = $batch_data['batch'] ;
$batch_next = $batch_data['batch_next'] ;
?>
<option value="<?php echo $batch;?><?php echo (isset($_REQUEST['batch']) && $_REQUEST['batch'] == ''.$batch.'') ? 'selected="selected"' : ''; ?>"><?php echo $batch."---".$batch_next;?></option>
<?php } ?>
</select>
Try to change your option value as below.
<option value="<?php echo $batch;?>"
<?php echo (isset($_REQUEST['batch']) && $_REQUEST['batch'] == $batch) ? "selected" : ''; ?>>
<?php echo $batch."---".$batch_next;?>
</option>
This question already has an answer here:
Select option default based on database variable [duplicate]
(1 answer)
Closed 7 years ago.
I'm beginner in PHP MySQL. I successfully get the value from database in INPUT type but I can't get the data from database in SELECT type:
Here is my sample edit form where Gender & User Type can't output the value from my database:
and here is data from the table I created:
I'm calling the data in my input box by using this code:
<?php $userRow['agentFname']; ?> //$userRow['ROW NAME IN TABLE'];
But I can't call the data where In select box, like Gender: and User Type here is my code of Select box.
<select class="form-control" name="aGender" >
<option selected disabled>*Gender</option>
<option>Male</option>
<option>Female</option>
</select>
<select class="form-control" name="utype" >
<option selected disabled>*User Type</option>
<option>Agent</option>
<option>Team Leader</option>
<option>Admin</option>
</select>
#Edmhar has a good answer, but it is hard coded and isn't good if you want to add more genders (transgenders and what not).
What I do is something like this:
<?php
$array = array("male", "female", "other");
echo "<select class='form-control' name='aGender' >";
foreach ($array as $gender) {
if ($gender == $databaseValue) {
echo "<option selected>$gender</option>";
} else {
echo "<option>$gender</option>";
}
}
echo "</select>";
?>
Also, don't use disabled on form elements; use read-only. It does the same thing as disabled visually, but disabled does what it says. It blocks the value from being submitted to the database. read-only just prevents editing, but doesn't cause form submission problems. User type will follow the same suit.
I already have my own answer to this
Here how I solved this:
<select class="form-control" name="aGender" >
<?php
if ($userRow['agentGender'] == 'Male') {
echo "<option selected>Male</option>";
echo "<option>Female</option>";
} else {
echo "<option selected>Female</option>";
echo "<option>Male</option>";
}
?>
</select>
I think you can use below conditional code for this issue:
<?php if($userRow['aGender'] == 'Male'){
$selectedMale = 'selected="selected"'
$selectedFemale = ''
}else{
$selectedFemale = 'selected="selected"'
$selectedMale = ''
}?>
<select class="form-control" name="aGender" >
<option selected disabled>*Gender</option>
<option <?php echo $selectedMale ;?>>Male</option>
<option <?php echo $selectedFemale;?>>Female</option>
</select>
and same for the another select box.
It will work hopefully.
In my opinion it's best to use ternary operator in such a case, combined with options element fetched from db/array. Something like:
<?php $options = Array(1 => "Option 1", 2 => "Option 2")
<select>
<?php foreach($options as $key => $opt): ?>
<option value="<?= $key ?>" ($key == $userRow['value'] ? "selected" : "" )><?= $opt ?></option>
<?php endforeach; ?>
</select>
I am adding a feature to edit the ads a user puts. For that I want to make the value selected which is selected by the user when he entered the values . How can I implement this?
<div class="nm">
Category
</div>
<div class="fl">
<select name="category" id = "ad_category" onchange="cangeSubCat(this.value)" >
<option value="">---Select Category---</option>
<option value="real_estate">Real Estate</option>
<option value="hotels_resturants">Hotels and Resturants</option>
<option value="car">Car Rental</option>
</select>
</div>
Add the selected HTML <option> attribute, in XHTML it is selected="selected".
<option value="value" selected>title</option>
^^^^^^^^
Documentation: http://www.w3.org/TR/html4/interact/forms.html#h-17.6.1
I mean how will I know which one should be selected..it will be different for different users . I wnt it to be selected which user selects during adding the ad
That depends on your code. You can do this with an array with all value/title pairs (value => title) and the value which is selected. Then when key (value) equals the selected one, the attribute is added in output. As it's an array it's easy to iterate over it.
$otpions = array(
'a' => 'A',
'b' => 'B',
);
$selected = 'b';
echo '<select>';
foreach ($options as $value => $title)
{
printf('<option value="%s" %s>%s</option>',
$value, $selected == $value ? 'selected' : '', $title);
}
echo '</select>';
okay lets assume you fetch value from db and that select box value is in $select variable then you've to write
<option <?php if($select=="real_estate") { echo "selected='selected'"; } ?> value="real_estate">Real Estate</option>
<option <?php if($select=="hotels_resturants") { echo "selected='selected'"; } ?> value="hotels_resturants">Hotels and Resturants</option>
<option <?php if($select=="car") { echo "selected='selected'"; } ?> value="car">Car Rental</option>
You can use this magic function
function __selectedDb($ctrlValue,$dbValue)
{
if($ctrlValue == $dbValue)
return "selected='selected'";
else
return "";
}
like
<select name="category" id = "ad_category" onchange="cangeSubCat(this.value)" >
<option value="" <?php echo __selectedDb("","$cat")?>>---Select Category---</option>
<option value="real_estate" <?php echo __selectedDb("real_estate","$cat")?>>Real Estate</option>
<option value="hotels_resturants" <?php echo __selectedDb("hotels_resturants","$cat")?>>Hotels and Resturants</option>
<option value="car" <?php echo __selectedDb("car","$cat")?>>Car Rental</option>
</select>
I write in core php please convert php code to smarty
How can I auto select a field in dropdown.
Say if someone goes to www.xyx/form/?abc
Some value gets selected in the dropdown,
Or if someone goes to www.xyx/form/?def
Some other value gets selected in the dropdown.
I am comfortable with JS and php.
assuming example.com/?sel=xxx
<?php
$sel = $_GET['sel'];
?>
<select ...>
<option val="xxx" <?php if($sel==='xxx') echo 'selected="selected"';?>>Option XXX</option>
<option val="yyy" <?php if($sel==='yyy') echo 'selected="selected"';?>>Option YYY</option>
</select>
No Javascript needed.
PHP
<select name="select">
<option value="abc"<?php ($_GET['select'] == 'abc'? echo 'selected="selected"' : ''); ?>>ABC</option>
<option value="def"<?php ($_GET['select'] == 'def'? echo 'selected="selected"' : ''); ?>>DEF</option>
</select>
<option value="abc" <?php echo isset($_GET['abc']) ? 'selected="selected"' : ''; ?>>abc</option>
hmmm, so what will you do when you have 100s of items in the Options list? The other ideas wont look so great then.
Then you will need to just simply write 1 line of code at the end of select tag:
<?php if(isset($_POST['env_foil_color'])) echo "<script>document.getElementById('env_foil_color').value='{$_POST['env_foil_color']}';</script>"; ?>
where, 'env_foil_color' is the select tag's ID and Name both
Im trying to implement the search feature in my website.
when the search keyword is entered in the textbox, and the category combo is selected, the form will be Posted and the result will be shown on the same page.
what i want is to keep the selected category of the combo by default in the form after posted
For eg., If i select the category 'Automobiles' in the combo and click search, after form submit, the combo should show the automobiles as default selected option. Please help me. Any help will be appreciated
I assume you get categories from database.
you should try:
<?php
$categories = $rows; //array from database
foreach($rows as $row){
if($row['name'] == $_POST['category']){
$isSelected = ' selected="selected"'; // if the option submited in form is as same as this row we add the selected tag
} else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$row['id']."'".$isSelected.">".$row['name']."</option>";
}
?>
Assuming that by "combo" you mean "A regular select element rendering as a drop down menu or list box" and not "A combobox that is a combination of a drop down menu and free text input":
When outputting the <option> elements, check the value against the submitted data in $_POST / $_GET and output selected (in HTML) or selected="selected" (in XHTML) as an attribute of the option element.
Here is the JQuery way I am using.
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
$("#name").val("<?php echo $_POST['name'];?>");
</script>
But this is only if you have jquery included in your webpage.
Regards
<?php
$example = $_POST["friend"];
?>
<form method="POST">
<select name="friend">
<option value="tom" <?php if (isset($example) && $example=="tom") echo ' selected';?>>Thomas Finnegan</option>
<option value="anna" <?php if (isset($example) && $example=="anna") echo ' selected';?>>Anna Karenina</option>
</select>
<br><br>
<input type="submit">
</form>
This solved my problem.
This Solved my Problem. Thanks for all those answered
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
$countries_uid = $_POST['countries_uid'];
while($row = mysql_fetch_array($result)){
$uid = $row['uid'];
$country = $row['country_name'];
$isSelected = null;
if(!empty($countries_uid)){
foreach($countries_uid as $country_uid){//cycle through country_uid
if($row['uid'] == $country_uid){
$isSelected = 'selected="selected"'; // if the option submited in form is as same as this row we add the selected
}
}
}else {
$isSelected = ''; // else we remove any tag
}
echo "<option value='".$uid."'".$isSelected.">".$country."</option>";
}
this is my solutions of multiple select dropdown box after modifying Mihai Iorga codes
After trying al this "solves" nothing work. Did some research on w3school before and remember there was explanation of keeping values about radio. But it also works for Select option. See here an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
Easy solution:
If select box values fetched from DB then to keep selected value after form submit OR form POST
<select name="country" id="country">
<?php $countries = $wpdb->get_results( 'SELECT * FROM countries' ); ?>
<option value="">
<?php if(isset($_POST['country'])){echo htmlentities($_POST['country']); } else { echo "Select Country *"; }?>
</option>
<?php foreach($countries as $country){ ?>
<option <?php echo ($_POST['country'] == $country->country_name ? 'selected="selected"':''); ?> value="<?php echo $country->country_name; ?>"><?php echo $country->country_name; ?>
</option>
<?php } ?>
</select>