Elegant way to add "selected" into a dropdrown form using PHP - php

I have a form that looks like this:
$guests = 2; // Just for testing
$form = 'Guests<br /><select name="guests">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
</select>';
But the list of guests can be up to 100, so I probably shouldn't do a check for which value is selected manually.
What would be a good way for me to make the selected value become the selected value when the user sees this form?
Thanks!

What I normally do with dynamic select menus is use a foreach loop over an array, and just check each item.
Something like:
$dropdownName = "guests"; //Name of dropdown
$defaultValue = "0"; //value to select if there isn't one already set
$items = array('name'=>'value', 'anotherName'=>'anothervalue'); //items, name=>value
echo '<select name="'.$dropdownName.'">'; //Start Select
$selectedItem = (isset($_POST[$dropdownName])?$_POST[$dropdownName]:$defaultValue); //If a value is set, use it, otherwise use the default
foreach ($items as $name=>$value) //build select
{
echo '<option value="'.$value.'"'.(($selectedItem == $value)?' selected="selected"':'').'>'.$name.'</option>';
}
echo '</select>';

$guests = 2; // Just for testing
$form = 'Guests<br /><select name="guests">';
for($i = 0; $i <= 100; $i++)
$form .= "<option value='$i'{$guest == $i ? ' selected=\'selected\'' : ''}>$i</option>";
$form .= '</select>';
EDIT: $i < 101 was pretty lame...

You can store the value this value in a hidden field and on document.ready(), you can assign the selected value of drop down top the value of hidden value.
A solution that works but may not be efficient for some users...

Related

How I explode this kind of string in PHP?

I have a dropdown to display price ranges for searching.
HTML for dropdown:
<select name="price">
<option value="">All (-)</option>
<option value="">Rs.400 to Rs.1,000 (3)</option>
<option value="">Rs.1,000 to Rs.2,000 (6)</option>
<option value="">Rs.2,000 to Rs.4,000 (1)</option>
<option value="">Rs.4,000+ (1)</option>
</select>
Using this option values, now I need to separate first and second price from user selection.
Eg. If someone select Rs.400 to Rs.1,000 (3), then I need to get 400 and 1,000.
Can anybody tell me how can I do this in php. I tired it with php explode. but I could not figure this out correctly.
Hope somebody may help me out.
Thank you.
What about something like this:
HTML
<select name="price">
<option value="all">All (-)</option>
<option value="400|1000">Rs.400 to Rs.1,000 (3)</option>
<option value="1000|2000">Rs.1,000 to Rs.2,000 (6)</option>
<option value="2000|4000">Rs.2,000 to Rs.4,000 (1)</option>
<option value="Over">Rs.4,000+ (1)</option>
</select>
PHP
<?php
//Get the data from the form
$price = $_POST['price'];
$prices = explode("|", $price);
?>
For example, if the user selects "Rs.400 to Rs.1,000", the value of $prices will be:
$price[0] = "400";
$price[1] = "1000";
I hope that helps. If it doesn't, I suppose I wasn't clear on what you were asking.
Inspired by a previous answer. I'd suggest.
HTML
<select name="price">
<option value="|">All (-)</option>
<option value="400|1000">Rs.400 to Rs.1,000 (3)</option>
<option value="1000|2000">Rs.1,000 to Rs.2,000 (6)</option>
<option value="2000|4000">Rs.2,000 to Rs.4,000 (1)</option>
<option value="4000|">Rs.4,000+ (1)</option>
</select>
PHP
<?php
function get_numeric($val) {
if (is_numeric($val)) {
return $val + 0;
}
return false;
}
$price_selected = isset($_REQUEST['price']) && trim($_REQUEST['price'])!="" ? $_REQUEST['price'] : "|"; // sets a default value
list($lower, $upper) = array_map('get_numeric',explode('|', $price_selected, 2));
var_dump($lower); // false when there's no lower limit
var_dump($upper); // false when there's no upper limit
?>

PHP-How to Display Current Selected Value in Form field

hi i have set up a php based form submission method for sorting rows per page in a select drop down menu, it is working fine i get to sort the rows according to value selected, but my problem is when a value is selected for sort it doesn't shows up in form selected field as whats currently selected.
what i mean to say is that when a value is selected in drop down menu for sorting rows it should show up as current in select-box as default value, and if nothing is selected then default row value should show up as current.
please see here here at the sorting method, it shows current(10) as default rows and when a value is selected it becomes as current on page reloads after querying database.
here is my html code for form field:
<form action="is-test.php" method="get">
<select name="rpp" onchange="this.form.submit()">
<option selected value="">show</option><!-- i want default & current selected value here -->
<option value="10">10</option>
<option value="20">20</option>
<option value="30">30</option>
</select>
</form>
and php code for this sorting is:
$rowsperpage = '';
if (isset($_GET['rpp'])&& is_numeric($_GET['rpp'])) {
$rowsperpage = (int) mysql_real_escape_string($_GET['rpp']);
}else{
$rowsperpage='5';
}
and mysql query for this is:
$sql2 = "SELECT * FROM $tablename ORDER BY $orderby $sortby LIMIT $rowsperpage OFFSET $offset";
please sugest me a way to set selected value as current value.
Thanks
In your <option> tags, you should performed checking like this:
<option value="10" <?php if ($rowsperpage == 10) echo 'selected="selected"' ?>>10</option>
<option value="20" <?php if ($rowsperpage == 20) echo 'selected="selected"' ?>>20</option>
<option value="30" <?php if ($rowsperpage == 30) echo 'selected="selected"' ?>>30</option>
So if you select 20, it will displayed as the current value of the <select>
<option value="10">10</option>
<option value="20" selected="selected">20</option>
<option value="30">30</option>
To make things simpler, just use for loop like this:
for ($i = 10; $i <= 30; $i+= 10) {
echo "<option value=\"$i\" ".($rowsperpage == $i ? 'selected="selected"' : '').">$i</option>";
}
<option selected value="<?php echo $rowsperpage; ?>"><?php echo $rowsperpage; ?></option>
A possibly better way to do this is with a loop:
for ($i = 10, $i <= 30; $i +=10) {
$selected = ($i == $rowsperpage) ? ' selected="selected"' : '';
echo sprintf('<option value="%d"%s>%d</option>', $i, $selected, $i);
}

select combo box based on get value

I'm using search with combo box
Here is my combo box source code
<select name="salary" class="styled">
<option selected="selected" value=''>Any</option>
<option value="10000">10,000</option>
<option value="20000">20,000</option>
<option value="30000">30,000</option>
<option value="40000">40,000</option>
<option value="50000">50,000</option>
<option value="60000">60,000</option>
<option value="70000">70,000</option>
<option value="80000">80,000</option>
<option value="90000">90,000</option>
<option value="100000">100,000</option>
<option value="110000">110,000</option>
<option value="120000">120,000</option>
<option value="130000">130,000</option>
<option value="140000">140,000</option>
<option value="150000">150,000</option>
</select>
I would like to select value based on $salary=$_GET['salary']; if $salary empty I need to select first one as selected
To set a default value for an HTML select element, you need to give the appropriate <option> element the selected attribute. It would look like this:
<option value='50000' selected='selected'>50,000</option>
In your PHP code, you would add this by setting a string for each option, to either "selected='selected'" or blank, depending on whether that option is the one you want to have selected.
This is obviously far easier to put into a loop rather than writing the same code twenty times, so you would need to rewrite your output to create a loop for creating your options.
Hope that helps.
You can do something like this on creation...[not tested]
<?php
$options = array(
'10000' => '10,000',
...
'150000' => '150,000'
); //From MySQL
array_unshift($options, '' => 'Any');
$salary = isset($_GET['salary'])?$_GET['salary']:'';
?>
<select name="salary" class="styled">
<?php foreach ($options as $value=>$text){ ?>
<option <?php if($value == $salary){echo 'selected="selected"'; }?> value="<?php echo $value; ?>"><?php echo $text; ?></option>
<?php } ?>
</select>
If I understand your question correctly you want that if the person doesn't select any thing you want 10000 to be automatically selected for him. And I also assume that the options in the select list are static. So..
<?php
if($_GET['salary']=='')
$salary = 10000;
else
$salary = $_GET['salary'];
?>

Get date, explode, use data to select options in <select>

I have three variables set, $date_legible (in the format of F jS, Y, i.e. January 1st, 2011), $date_timestamp (self-explanatory), and $date_normal (in the format of YYYY-MM-DD)
I have three select fields:
<select name="date_mo">
<option value="01">January</option>
<option value="02">February</option>
<option value="03">March</option>
<option value="04">April</option>
<option value="05">May</option>
<option value="06">June</option>
<option value="07">July</option>
<option value="08">August</option>
<option value="09">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
<select name="date_dy">
<option value="01">1</option>
<option value="02">2</option>
<option value="03">3</option>
<option value="04">4</option>
<option value="05">5</option>
<option value="06">6</option>
<option value="07">7</option>
<option value="08">8</option>
<option value="09">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
<option value="21">21</option>
<option value="22">22</option>
<option value="23">23</option>
<option value="24">24</option>
<option value="25">25</option>
<option value="26">26</option>
<option value="27">27</option>
<option value="28">28</option>
<option value="29">29</option>
<option value="30">30</option>
<option value="31">31</option>
</select>
<select name="date_yr">
<?php for($year=$curryear;$year<$curryear+51;$year++){ ?>
<option value="<?php echo $year; ?>"><?php echo $year; ?></option>
<?php } ?>
</select>
I know I want to convert the timestamp, but I will ultimately need to explode the output for the $month, $day, and $year. The problem is I don't know how to check the selects to the values and automatically select the correct option.
Can anyone help? Thanks!
UPDATE
I now have one more variable, because I'm having users submit from the front end, and Gravity Forms submits as YYYY-MM-DD.
Prior to diving into the solutions already posted (thank you guys [and gals] by the way), here's a little more information:
I'm running WordPress and have three custom fields as described above. When a user submits a post from the front end, the only custom field that's filled out is $date_normal. This is okay, because a post has to be moderated (i.e. published) from the backend. What I NOW need is on load to set the YYYY-MM-DD to set the options on the select. I'm not asking you guys to alter your answers, I'm sure I can figure it out (though if you can help with this new problem, it would be greatly appreciated).
If I understand your question correctly, you have a timestamp and you need to use the timestamp to select the appropriate select options when you render the page.
As a forewarning - this will make it possible to select invalid dates, for example February 31st (does not exist). You may want to consider re-drawing the year drop-down when the month is changed using javascript. Since you didn't specify any javascript library (and it is not clear how important the possibility of an invalid date is), I will not venture to show code for that, but it would not be terribly difficult.
// using the current time for the sake of the example, your timestamp would take the place of this
$timestamp = time();
// determine the selected month, day, and year
$selected_month = date('n', $timestamp);
$selected_day = date('j', $timestamp);
$selected_year = date('Y', $timestamp);
// now, create the drop-down for months
$month_html = '<select name="date_mo">';
for ($x = 1; $x < 13; $x++) {
$month_html .= '<option value='.$x.($selected_month == $x ? ' selected=true' : '' ).'>'.date("F", mktime(0, 0, 0, $x, 1, $selected_year)).'</option>';
}
$month_html .= '</select>';
// output
print $month_html;
// create the day drop-down
$day_html = '<select name="date_day">';
for ($x = 1; $x < 32; $x++) {
$day_html .= '<option value='.$x.($selected_day == $x ? ' selected=true' : '' ).'>'.$x.'</option>';
}
$day_html .= '</select>';
// output
print $day_html;
// create the year drop-down
$year_html = '<select name="date_year">';
$start_year = date('Y', time());
$max_year = $start_year + 51;
for ($x = $start_year; $x < $max_year; $x++) {
$year_html .= '<option value='.$x.($selected_year == $x ? ' selected=true' : '' ).'>'.$x.'</option>';
}
$year_html .= '</select>';
// output
print $year_html;
Output:
EDIT
If your source data will be in the format of YYYY-MM-DD. In order to translate that into a timestamp, and thus work with the example code I've posted, is to call strtotime on that formatted date value. Thus, the only line in the code above that would need to be changed is $timestamp = strtotime($the_formatted_date);
<?php
// $months = array(1 => 'January', 2 => 'February', ... etc
?>
<select name="date_mo">
<? for ($i = 1, $current = (int) date('n'); $i <= 12; $i++) { ?>
<option value="<?=$i;?>"<?=($current === $i ? ' selected="selected"' : NULL);?>><?=$months[$i];?></option>
<? } ?>
</select>
<select name="date_dy">
<? for ($i = 1, $current = (int) date('j'); $i <= 31; $i++) { ?>
<option value="<?=$i;?>"<?=($current === $i ? ' selected="selected"' : NULL);?>><?=$i;?></option>
<? } ?>
<select name="date_yr">
<? for ($i = $current = (int) date('Y'), $until = $i + 50; $i <= $until; $i++) { ?>
<option value="<?=$i;?>"<?=($current === $i ? ' selected="selected"' : NULL);?>><?=$i;?></option>
<? } ?>
</select>
I would personally convert the 3 fields to a more user-friendly date selector (using for example jQuery UI), but to have the correct option selected when you open the page, you need to add a check to each option.
Example for the year:
<?php
$selected_year = date("Y", $date_timestamp); // get the selected year
for($year=$curryear;$year<$curryear+51;$year++)
{
?>
<option value="<?php echo $year; ?>" <?php echo ($selected_year == $year) ? 'selected' : ''; ?>><?php echo $year; ?></option>
<?php
}
?>

How repopulate/reselect/autoselect the multiple select box values on basis of csv from database?

I have a form which is displayed when there is some editing is required in data. This form contains the multiple select box field i.e.,
<select name="multiple" multiple>
<option value="1">asd</option>
<option value="2">asaad</option>
<option value="3">aslan</option>
</select>
Now when i come to this form, I get every existing values populated in their respective fields but i do not get this multiple select box populated. In db the its respective values are stored in csv format like, 2,3,4.
Now how Can i use these csv and repopulate the multiple select box respective of the csv.?
<?
$csvString = "1,3";
?>
<select name="multiple" multiple>
<option value="1" <?=strpos($csvString ,'1')!== false?'selected="selected"':''?> >Option 1</option>
<option value="2" <?=strpos($csvString ,'2')!== false?'selected="selected"':''?> >Option 2</option>
<option value="3" <?=strpos($csvString ,'3')!== false?'selected="selected"':''?> >Option 3</option>
</select>
I assume you generate HTML for selectbox iterating over the $options. Then you just have to check in each iteration if the current value is present in you $csv and add the selected parameter to the option.
$selection = explode(',', $csv);
foreach ($options as $value => $name) {
$selected = in_array($value, $selection) ? ' selected="selected"' : '';
echo '<option value="'. $value .'"'. $selected .'>'. $name .'</option>';
}
This may help but there is probably a better way...
$csvString = "1,3";
$options = explode(",", $csvString);
foreach($options as $val) {
${"opt".$val} = "selected=\"selected\"";
}
?>
<select ...>
<option value="1" <?php echo $opt1 ?> >Option 1</option>
<option value="2" <?php echo $opt2 ?> >Option 2</option>
<option value="3" <?php echo $opt3 ?> >Option 3</option>
</select>

Categories