I have the code to select the values from a database for populating my drop down list. But my question is if I stored the value of what the user selected in another database, how would I go about pulling that back out and making that the selected choice.
<select name="dropdown1" id="dropdown1">
<?php
for ($i = 0; $i < 5; $i++)
{
print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'.$options[$i]["Name"].'</option>'."\n";
}
?>
</select>
So the users stored value is lets say red. How would I make red the selected value as it populates my drop down list?
Thanks e
<select name="dropdown1" id="dropdown1">
<?php
$selected = "red";
for ($i = 0; $i < 5; $i++)
{
if ($options[$i]['Value'] == $selected) {
print '<option selected="selected" id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'.$options[$i]["Name"].'</option>'."\n";
} else {
print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'">'.$options[$i]["Name"].'</option>'."\n";
}
}
?>
</select>
On each element test the value. If the value is selected, print 'selected'.
<select name="dropdown1" id="dropdown1">
<?php
$selected = 'red';// obviously replace with DB value.
for ($i = 0; $i < 5; $i++)
{
// start as normal
print '<option id="'.$options[$i]["ID"].'" value="'.$options[$i]["Value"].'"';
// if this one is selected, add 'selected' to the tag.
// NOTE: booleans in HTML do not need to have an attribute value.
// so selected="selected" is not necessary here.
if( $options[$i]["Value"] == $selected ) print ' selected';
// finish as normal
print '>'.$options[$i]["Name"].'</option>'."\n";
}
?>
</select>
As a side note: if you use foreach it will make for smaller, more compact, and often faster code:
//this assumes that you want to iterate the whole options array
foreach( $options as $option )
{
print '<option id="'.$option["ID"].'" value="'.$option["Value"].'"';
if( $option["Value"] == $selected ) print ' selected';
print '>'.$option["Name"].'</option>'."\n";
}
Related
My code:
<label>Year: </label>
<?php
print '<select>';
$start_year = date('1910');
for ($y = $start_year; $y <= ($start_year + 104); $y++) {
print "<option value=\"$y\">$y</option>";
}
print '</select>';
?>
and our professor wants us to incorporate it being sticky with something like a code like this:
echo "<option value=\"$option\"";
if ($messageType == $option){
//make it sticky
echo ' selected="selected"';
}
echo ">$option</option>";
however that code isn't working with my code and i can't seem for it to become a default value/sticky.
In your for loop:
for ($y = $start_year; $y <= ($start_year + 104); $y++) {
($y== $option) ? echo '<option value="'.$y.'" selected="selected">'.$y.'</option>' : echo '<option value="'.$y.'">'.$y.'</option>';
}
I assumed that the value of $option is a year available in your for loop.
I hate to post an entire answer for this but i cannot comment yet... Given your problem "can't seem for it to become a default value" My money on its a very simple issue
echo ' selected="selected"';
should just be
echo ' selected';
http://www.w3schools.com/tags/att_option_selected.asp
but view source on the webpage it generates and make sure the HTML is generating as expected otherwise
I am trying to echo out "selected" on a value inside my array, within a foreach. If the form is false and my customer has already entered a particular value in my select, return it so he doesn't fill it again! That's what I am trying to do...
<?php
$marques = array('Word','Word1','Word20','Word46','Word9797');
foreach ($marques as $marque => $value)
{
if (isset($_POST['marque']) && $_POST['marque'] == $value[$_POST['marque']]) {
echo '<option value="'.$_POST["marque"].'">'.$value[$_POST["marque"]].'</option>';
}
echo '<option value="'.$marque.'">'.$value.'</option>';
}
?>
<?php
$marques = array('Word', 'Word1', 'Word20', 'Word46', 'Word9797');
foreach ($marques as $marque)
echo '<option value="'.$marque.'" '.(($marque == $_POST['marque']) ? 'selected' : '').'>'.$marque.'</option>';
?>
You mean this?
<?php
$marques = array('Word','Word1','Word20','Word46','Word9797');
foreach ($marques as $marque => $value) {
$setItSelected = '';
if (isset($_POST['marque']) && $_POST['marque'] == $marque) {
$setItSelected = 'selected';
}
echo '<option value="'.$marque.'" '.$setItSelected.'>'.$value.'</option>';
}
?>
Changing what's inside the value attribute doesn't make the item more or less selected. You need to add the selected attribute, see http://www.w3schools.com/tags/att_option_selected.asp
The output:ed html should look something like:
<option value="id" selected>some text</option>
<?php
$marques = array('Word','Word1','Word20','Word46','Word9797');
foreach ($marques as $marque)
{
if (isset($_POST['marque']) && $_POST['marque'] == $marque')
echo '<option value="'.$marque.'" selected>'.$marque.'</option>';
else
echo '<option value="'.$marque.'">'.$marque.'</option>';
}
?>
Your Array is one dimension, you can't use "=>"
For select option you must add the "selected" attribute too at your option tag
I have a dropdown control which and I would like it to default to a specific option based on the access of the logged in user. For example, the dropdown has 10 options but only administrators have access to view all 10 options. The majority of users only have access to 1 of the options though. The page contents are hidden/displayed based on whether or not the value of the dropdown is null.
Question: Using the example above, if an admin is logged in I need the dropdown to default to "Select an option". This way the page content is hidden. On the other hand, if a user with access to only 1 is logged in, I need it to default to that 1. This way they don't have to select anything and, by default the page content is displayed. How do I go about doing this?
Below is my current code which handles what the dropdown displays based on when a selection is made.
PHP/HTML
// Hide/Show main content div
<?php
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) { // If value is null, default to 'Select an option'
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
while ($row = odbc_fetch_array($db)) {
echo "<option value=\"".$row['content']."\">".$row['content']."</option>";
}
} else { // If value not null keep the selected value selected
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
// Pass selected value on change
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
SQL
// Hardcoding user for testing purposes, THIS WILL BE CHANGED
function getOptions() {
$results = "SELECT content, userid FROM table WHERE userid = 'username'";
return $results;
}
Any help is much appreciated and please let me know if I'm not clear about anything.
Got some help and have it figured out now. Here is the revised code:
PHP/HTML
// Hide/Show main content div
<?php
$src = null;
if (isset($_GET['src'])) {
$src = $_GET['src'];
} else {
?>
<style>
#divmain { display: none; }
</style>
}
<?php } ?>
// Start of form, header, etc.
<select name="select1" id="select1">
<?php
$sql = getOptions();
$data = makeConnection($sql);
if ($src == null) {
$i = 0;
$content = "";
while ($row = odbc_fetch_array($db)) {
$content .= "<option value=\"".$row['content']."\">".$row['content']."</option>";
$i++;
}
if ($i > 1) {
echo "<option selected value=\"\" disabled=\"disabled\">--Select an option--</option>";
}
echo $content;
if ($i > 1) { $oneopt = 1; }
else { $oneopt = 0; }
} else {
while ($row = odbc_fetch_array($db)) {
if ($row['content'] == $src) { $selected = " selected "; }
else { $selected = " "; }
echo "<option value=\"".$row['content']."\" ".$selected.">".$row['content']."</option>";
}
}
?>
</select>
JS
$('#select1').change(function() {
var sel = $(this).val();
location.href = "page1.php?src=" + sel;
}
<?php
global $optone;
if ($optone == 1) {
echo "$('#select1').trigger('change');";
}
?>
SQL -- Stays the same
#chenasraf really appreciate the help! Hope this can be of some help to someone in the future!
The preselected option is always the first to have a "selected" attribute. Your first disabled one has it first on all cases, so it's always chosen. Remove that and work from there.
On a side note, I think you can manage to make this options part work better. I've taken the liberty of rewriting it for you:
<select name="select1" id="select1">
<?php
$selected = '';
while ($row = obdc_fetch_array($db)) {
$options[] = '<option value="'.$row['content'].'">'.$row['content'].'</option>';
if ($row['content'] == $src)
$selected = count($options) - 1;
}
array_unshift($options, '<option disabled="disabled"', $selected == '' ? ' selected="selected"' : '','>--Select an option--</option>');
foreach ($options as $option) {
echo $option;
}
?>
</select>
Using select and option HTML tags, I pass information through using $_POST.
When reloading the page however, the select resets back to the original values.
I am looking to get it to remember what has been passed through.
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo"<option value='$value-$first-$second'>$title - $first - $second</option>";
}
}
}
?>
As you can see, I use 3 foreach loops to populate whats in it.
How can I achieve my selection being remembered?
Thanks for reading.
You'll need to use the name of your select field in place of "your_select_field_name" in my change below:
<?php
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
echo "<option value='$value-$first-$second'";
if( $_POST['your_select_field_name'] == "$value-$first-$second" ) {
echo ' selected="selected"';
}
echo ">$title - $first - $second</option>";
}
}
}
?>
The output for the selected option on the new page needs to look like:
<option value='foo' selected>...<option>
HTML does not have memory. The item that's selected by default in a <select> form element is the one with the selected attribute (or the first one if none). Simply use the information contained in $_POST to generate the appropriate markup:
<select name="foo">
<option value="v1">Label 1</option>
<option value="v2">Label 2</option>
<option value="v2" selected="selected">Label 3</option>
<option value="v4">Label 4</option>
</select>
You need to set the selected tag on the correct option. Something like this:
<?php
$postedValue = $_POST['select_name'];
foreach($data as $value => $title)
{
foreach($ag as $first)
{
foreach($af as $second)
{
$computedValue = $value . '-' . $first . '-'. $second;
if ( $computedValue == $postedValue) {
$selected = "selected";
} else {
$selected = ''
}
echo "<option value='$computedValue' $selected>$title - $first - $second</option>";
}
}
}
?>
It could probably be written cleaner but this is the general idea.
I have a select box that shows 3 options: option1, option2, option3. When a user hits submit, then in $_POST I do have the value selected. Is there an easy way to redisplay the select box with the chosen option highlighted WITHOUT it being repeated in the options?
In other words, if option2 is selected and submit is clicked, the page should display again with option2 selected, and option1 and option 3 underneath.
Thanks.
<?php
$arrValues = array(...);
$selectedValue = (isset ($_POST['selectName']) ? $_POST['selectName'] : "");
?>
<select name="selectName">
<?php
for ($i = 0; $i < count($arrValues); $i++)
{
$opts = ($arrValues[$i] == $selectedValue) ? ' selected="selected"': '';
echo '<option value="' . $arrValues[$i] . '"' . $opts . '>' . $arrValues[$i] . '</option>';
}
?>
</select>
Create your options like this.
$options = array("optionvalue" => "Option Name");
foreach($options as $value => $name)
{
if(isset($_POST['select_box']))
{
if($_POST['select_box'] == $value)
{
echo '<option selected="selected" value="'.$value.'">'.$name.'</option>';
continue;
}
}
echo '<option value="'.$value.'">'.$name.'</option>';
}
When you generate the select box, use the POST data (if available) to pick the item that's selected (and/or to sort the items).
Kind of like:
if($_POST["optval"] == $opt) $sel = "selected='selected'"; else $sel = "";
print "<option value='$opt' " . $sel . ">$opt</option>";
Naturally you'd want to verify that the POST data is valid and that it exists (isset). Assuming of course that you generate your select box from data accessible by PHP, rather than statically define it.