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";
Related
I am trying to select a previously selected value inside dropdown selection using php. My code is as follows
<?php
$selected_val = "Assistant Professor";
function generateSelect($type = 'text', $name = 'desgntn', $id = 'fac_dsgn', $options = array(), $default) {
$html = '<select type="'.$type.'" name="'.$name.'" id="'.$id.'">';
foreach ($options as $option ) {
if ($option == $default) {
$html .= '<option value='.$option.' selected="selected">'.$option.'</option>';
} else {
$html .= '<option value='.$option.'>'.$option.'</option>';
}
}
$html .= '</select>';
return $html;
}
$list = array("Lecturer", "Assistant Professor", "Associate Professor", "Professor", "Assistant Professor (On Leave)", "Associate Professor (On Leave)", "Professor (On Leave)");
$res = generateSelect('text', 'desgntn', 'fac_dsgn', $list, $selected_val);
echo $res;
?>
But the problem is I am always getting the first word of a multi spaced option inside value attributein option tag of html. for example: I am getting Assistant inside value tag for Assistant Professor. Is there any way so that I can always get the actual value with spaces?
I believe you forgot to enclose the option value in quotes:
it should be something like
$html .= '<option value="'.$option.'" selected="selected">'.$option.'</option>';
(note the double quotes around $option)
Hope it helps
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 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
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