I want to fetch dropdown list in ajax call using PHP code.
$outputRes = '';
$reminderDetails["interval_type"] = value of dropdown this may varies. I want to keep value selected="selected"
Below is my expected output from ajax call
$outputRes .= '<select id="reminder_int_type" name="reminder_int_type" class="change">
<option value="1" '.if($reminderDetails["interval_type"] == 1){ \'selected="selected"\'; }.'>days</option>
<option value="2">Hours</option>
<option value="3">Minutes</option>
</select>';
echo $outputRes; exit;
I may use code like below but i have many options tag so doesn't look feasible to me
$outputRes .= '<select id="reminder_int_type" name="reminder_int_type" class="change">
<option value="1" ';
if($reminderDetails["interval_type"] == 1){ $outputRes .= 'selected="selected"';}
$outputRes .= '>days</option>
<option value="2">Hours</option>
<option value="3">Minutes</option>
</select>';
echo $outputRes; exit;
I have problem in writting right syntax .
Based on your code, you can do it this way:
$outputRes = '';
$reminderDetails["interval_type"] = value of dropdown this may varies. I want to keep value selected="selected"
$interval = array("Days", "Hours", "Minutes");
$outputRes .= '<select id="reminder_int_type" name="reminder_int_type" class="change">';
foreach ($interval as $k => $v) {
$k = $k + 1; // to keep your values beginning at 1.
$outputRes .= '<option value="'.$k.'"'
if ($reminderDetails["interval_type"] == $k) {
$outputRes .= 'selected="selected"';
}
$outputRes .= '>';
$outputRes .= $v
$outputRes .= '</option>';
}
$outputRes .= '</select>';
You may want to return JSON instead and parse it on the browser side. See json_encode
$reminderDetails["interval_type"] = 'value of dropdown this may varies. I want to keep value selected="selected"';
$result = array('array from which you want to create a dropdown');
$outputRes = '<select id="reminder_int_type" name="reminder_int_type" class="change">';
foreach($result as $optionValue=>$optionName)
{
$is_selected = ($reminderDetails["interval_type"] == $optionValue)?'selected':'';
$outputRes .= "<option value=$optionValue $is_selected>$optionName</option>"
}
$outputRes . ="</select>";
echo $outputRes; exit;
I hope you get some idea .. I am assuming that you are creating dropdown dynamically out of a array
Related
How can i create a Multiple select box from 2 arrays
1st array contains all values and the second array contains the values that will be marked as selected in multiple select
$a=array[1,2,3,4,5,6,7,8];
$b=array[3,7,8];
the multiple selectbox will have all the values from array $a but values from array $b will be selected.
Any way to achieve this ?
You can use this code
$a=array(1,2,3,4,5,6,7,8);
$b=array(3,7,8);
$selected="";
foreach($a as $val)
{
if(in_array($val,$b))
{
$selected = 'selected="selected"';
}
//Code for create multi select drop down and echo $selected in option like
<option $selected value="" ></option>
}
$a=array(1,2,3,4,5,6,7,8);
$b=array(3,7,8);
$html = '<select multiple>';
foreach($a as $val)
{
$selected = (in_array($val,$b)) ? 'selected' : '';
$html .= '<option value="' . $a . '"' . $selected . '>' . $a . '</option>';
}
$html .= '</select>';
echo $html;
I have a selectbox with some values, i inserted those values inside an array.
Now i want to select some specific option, and keep the option selected even when the page reloads.
$logos =array('logo1', 'logo2', 'logo3');
echo '
<td class="jofftd">
<label>Platform</label>
<select name="searchpt">
<option value="0">All</option>
';
foreach ($logos as $value)
{
echo '
<option value="'.$value.'">' .$value . '</option>
';
}
echo '
</select>
</td>';
I would need to do something like this:
foreach ($logos as $value)
{
echo '
<option';
if ($value == $value) echo 'selected="selected"';
echo 'value="'.$value.'">' .$value . '</option>
';
}
But it doesn't work.
Thanks.
Assuming you are using a POST method form, the code would look something like this (note: not tested)
foreach ($logos as $value)
{
$selected = ($value == $_POST['searchpt']) ? ' selected' : '';
echo '<option'. $selected . ' value="'.$value.'">' .$value . '</option>';
}
If nothing else, you're missing at least one space character:
<option';
if ($value == $value) echo 'selected="selected"';
This will produce
<optionselected="selected"
which is not exactly valid HTML.
Plus, $value==$value will always be true, so even if you had proper spacing in the tags, you'd be marking ALL of the options as selected. You need to compare the $value from the loop against the value from the original form, e.g.
if ($value == $_POST['field_from_previous_form'}) { ... }
$value == $value will be always true and it will always add selected = "selected"
use string concatenation to form select form field.
<?php
$logos =array('logo1', 'logo2', 'logo3');
$value = 'logo1';
$str = '<select name="searchpt"><option value="0">All</option>';
foreach ($logos as $value)
{
$str.='<option ';
if ($value == 'logo1')
$str.=' selected="selected "';
$str.=' value="'.$value.' ">' .$value . ' </option> ';
}
$str.='</select>';
echo $str;
?>
Hope this code snippet will solve your problem
I'm using PHP to generate the select menu for an HTML web form as follows:
$foods = array(
'1' => 'fruit',
'2' => 'pizza',
'3' => 'bread',
'4' => 'nuts',
);
Here's the code for the HTML select input:
<select id="food" name="food">
<option value="*">- No Selection - </option>
<?php
$output = "";
$selected = false;
foreach($foods as $food => $value) {
$food = htmlspecialchars($food);
$output .= "<option value=\"$food\"";
if ($food == $pcSymptomSearch) {
$selected = true;
$output .= " selected";
}
$output .= ">$value</option>";
}
echo $output;
?>
</select>
I've noticed when viewing the source in Safari/Mac OS X that the select input generated by PHP appears on one line like this, which makes reading/debugging a bit tricky:
<option value="1">fruit</option><option value="2">pizza</option><option value="3">bread</option><option value="4">nuts</option> </select>
Is there a way to make each option appear on one line like this:
<option value="1">fruit</option>
<option value="2">pizza</option>
<option value="3">bread</option>
<option value="4">nuts</option>
</select>
All you have to do is when you are building your string for output add a \n (newline character) every place that the newline would be appropriate.
$output .= ">$value</option>\n";
Replace:
$output .= ">$value</option>";
with
$output .= ">$value</option>\n";
I have a dropdown section menu that I need to set the selected value based on the database values.
I have a table with the following structure: id, pid, disporder, title, url
I am then using this code for the dropdown:
echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
echo "<option value=\"".$parent['id']."\">".$parent['title']."</option>";
}
echo "</select>";
How would I go by getting the selected value based on what's in the database?
I have multiple entries in the table, so using an array with values (similar to this), isn't what I want to use:
$options = array('1', '2', '3');
foreach($options as $option)
{
if($option = $parent['id'])
{
echo "selected";
}
else
{
echo "";
}
Thanks.
You haven't really given enough info to really say what the exact solution would be. If you're creating a select tag in PHP though, the typical pattern for building the markup is:
<?php
$options = get_me_some_options();
$select_markup = '<select name="my-select" id="my-select>';
foreach ($options as $key => $val) {
$selected = '';
if (is_this_selected($val)) {
$selected = 'selected';
}
$select_markup .= "<option $selected val=\""
. $val['id'] . "\">" . $val['name'] . '</option>';
}
echo $select_markup . "</select>";
It looks like your use case is similar, but slightly more complex. Ultimately though what matters is that, inside the loop, you have some way to determine whether a given row should be 'selected' or not.
If I understand correctly, you want to compare each $parent['id'] with the values of an array called $options. Try this:
$options = array('1', '2', '3');
echo "<select name=\"parent\" id=\"parent\">\n";
echo "<option value=\"0\">No Parent</option>";
$query = $db->simple_select("navbar", "*", "pid='0'");
while($parent = $db->fetch_array($query))
{
$selected = ( in_array($parent['id'], $options) ? ' selected' : '';
echo "<option value=\"".$parent['id']."\"$selected>".$parent['title']."</option>";
}
echo "</select>";
If you're trying to use this in multiselects then this might help
<?php
$optionsToSelect=array(1,2,3);
?>
<select name="parent" id="parent">
<?php
foreach($allOptions as $opt){
?>
<option value="<?php echo $opt['value'];?>" <? echo $opt['selected']==1?'selected="selected"':'';?>><?php echo $opt['optTitle'];?><option>
<?php
}
?>
</select>
I`m using this code to repopulate drop down list from the database :
$city_id = 15;
while($row = mysql_fetch_assoc($result)) {
$selected = ($row['city_id'] == $city_id) ? 'selected="selected" ' : NULL;
echo '<option value="'.$city_id .$selected . '">"'.$row['city_name'].'"</option>\n';
}
It`s work like a charm but my question is are they more elegance solutions ?
Other than improving the indentation of the code, this is fine.
$city_id = 15;
while($row = mysql_fetch_assoc($result))
{
$selected = ($row['city_id'] == $city_id) ? ' selected="selected"' : NULL;
echo '<option value="' . $row['city_id']. '"' . $selected . '>'.$row['city_name'].'</option>\n';
}
Well, a more elegant solution would be to have a "controller" file that fetches all the cities an puts them into an array/object list/whatever. Then, in a "view" file, you iterate over that variable. That way, you separate a bit more the presentation from the logic.
In view:
<select name=student value=''>Student Name</option>
<?php foreach($cities as $city): ?>
<option value="<?php echo $city->id ?>" ><?php echo $city->name ?></option>
<?php endforeach; ?>
</select>
Also, I'd highly recommend using PDO for DB access.
I always use a function, since select boxes are something I end up creating a lot...
function select($name, $default, $values, $style='', $param='') {
$html = '<select name="'.$name.'" style="'.$style.'" '.$param.' >';
foreach($values as $i => $data) {
if (isset($data['noFormat'])) {
$html .= '<option value="'.$data['value'].'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.$data['text'].'</option>';
} else {
$html .= '<option value="'.htmlentities($data['value']).'" '.(($data['value']==$default)?'SELECTED="SELECTED"':'').' '.
(isset($data['style']) ? ' style="'.$data['style'].'" ' : '').'>'.htmlentities($data['text']).'</option>';
}
}
$html .= '</select>';
return $html;
}
Then loop through your query to build the array like this:
$default[] = array('value' => '0', 'text' => 'Select a City...');
while($row = mysql_fetch_assoc($result)) {
$list[] = array('value' => $row['city_id'], 'text' => $row['city_name']);
}
$list = array_merge($default,$list);
And finally an example to create the HTML:
select('select','form_el_name',$list['0'],$list,'font-size:12px;','onChange="document.forms[0].submit();"');
Hope it helps!
mysql_fetch_assoc to mysql_fetch_array
add proper comments
use standard php class ezsql or simple class tuts
$query="SELECT name,id FROM student";
/* You can add order by clause to the sql statement if the names are to be displayed in alphabetical order */
$result = mysql_query ($query);
echo "<select name=student value=''>Student Name</option>";
// printing the list box select command
while($nt=mysql_fetch_array($result)){//Array or records stored in $nt
echo "<option value=$nt[id]>$nt[name]</option>";
/* Option values are added by looping through the array */
}
echo "</select>";//Closing of list box