Multiple Select box from2 Arrays - php

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;

Related

Input <select> selected is not working correctly in PHP by comparing 2 arrays

I have
3 <select></select>
with 8 options inside (Array_1 with 8 position). All options value are the same.
What i am trying to do is that I want to make the Value in Array_2 to be the Selected value.
However, looks like my loop is not working correctly.
$array_1[]="value1";
$array_1[]="value2";
$array_1[]="value3";
$array_1[]="value4";
$array_1[]="value5";
$array_1[]="value6";
$array_1[]="value7";
$array_1[]="value8";
$array_2[]="value1";
$array_2[]="value3";
$array_2[]="value4";
for($i=0;$i<count($array_2);$i++){
echo '<select name="product_header_image[]">';
for($b=0;$b<count($array_1);$b++){
if(in_array($array_2[$i],$array_1)){
echo '<option selected VALUE="'.$array_1[$b].'" >'.$array_1[$b].'</option>';
}else{
echo '<option VALUE="'.$array_1[$b].'" >'.$array_1[$b].'</option>';
}
}
echo '</select>';
echo '<br>';
}
Anyone know whats wrong with my coding? what I want to achieve is the right hand side of the screenshot.
You need to replace this check:
if(in_array($array_2[$i], $array_1)) {
...
}
on this:
if($array_2[$i] == $array_1[$b]) {
...
}
Demo here
Not sure I understand your scenario, but this might be what you are looking for. It generates a dropdown with all the elements from both arrays, and highlights the selected ones.
$array_1[]="value1";
$array_1[]="value2";
$array_1[]="value3";
$array_1[]="value4";
$array_1[]="value5";
$array_1[]="value6";
$array_1[]="value7";
$array_1[]="value8";
$array_2[]="value1";
$array_2[]="value3";
$array_2[]="value4";
echo '<select name="product_header_image[]" multiple>';
foreach ($array_1 as $elem1) {
echo '<option VALUE="'. $elem1 .'" >' . $elem1 .'</option>';
}
foreach ($array_2 as $elem2) {
$selected = '';
if( in_array($elem2, $array_1) ) $selected = 'selected ';
echo '<option '. $selected . 'VALUE="' . $elem2 . '" >'.$elem2.'</option>';
}
echo '</select>';
echo '<br>';

Need to perform an if statement inside a php foreach loop

I'm working with the Filemaker API - which is similar to sql - basically its pulling data from a fields and from a list.
I'm trying to set up an if statement inside my foreach loop so that it adds a the tag selected="selected" to my select option in my html
Here's the code
<?php
$layout =& $fm->getLayout('Leads');
$values = $layout->getValueList('LeadStatus');
$list_menu = '<select name="LeadDocStatusSelect">';
foreach ($values as $value)
{
$list_menu .='<option value="' . $value . '">' . $value . '</option>' ;
}
$list_menu .= '</select>';
echo $list_menu;
?>
How can I add an if statement like this to the foreach loop?
if ($businessJudgements == 'No') {
echo 'checked="checked"';
} else {
echo '';
}
The body of the foreach loop is simply a block of statements so you can put in as many as you want, such as with:
foreach ($values as $value) {
$list_menu .='<option value="' . $value . '">' . $value . '</option>';
if ($businessJudgements == 'No') {
echo 'checked="checked"';
} else {
echo '';
}
}
However, are you sure you have the right attribute for the option tag? If it's your intent to select a specific option, checked is not the right method (it's meant for checkbox input fields). The selected attribute is the correct one for the HTML option tag.
So you would be better off with something like:
# The default is orange.
$default_value = "orange";
# Process every option.
foreach ($values as $value) {
# Add [<option value="X"].
$list_menu .= '<option value="' . $value . '"';
# Add [ selected] ONLY for default one.
if ($value == $default_value) {
$list_menu .= ' selected';
}
# Add [>X</option>].
$list_menu .= '>' . $value . '</option>';
}
This will give you the option tags as desired but the one where the value matches the default value will also have the selected attribute attached.
Assuming $values held the array {"red", "black", "orange", "yellow"}, you would end up with (formatted nicely here for the purposes of the answer):
<option value="red"> red </option>
<option value="black"> black </option>
<option value="orange" selected> orange </option>
<option value="yellow"> yellow </option>
I assuming that you already know how to get your $businessJudgement , so that code should be something like this
<?php
$layout =& $fm->getLayout('Leads');
$values = $layout->getValueList('LeadStatus');
$list_menu = '<select name="LeadDocStatusSelect">';
foreach ($values as $value)
{
if ($businessJudgements == 'No') {
$list_menu .='<option value="' . $value . '">' . $value . '</option>' ;
} else {
$list_menu .='<option value="' . $value . '" selected >' . $value . '</option>' ;
}
}
$list_menu .= '</select>';
echo $list_menu;
?>

Keep option selected

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

Return select dropdown in ajax call PHP

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

Modify function which dynamically populates select elements to use arrays from db

I'm trying to modify a function that I've been using to dynamically populate <select> element to use arrays from a database. The original function used hard-coded arrays to populate the elements, and pre-selected the option which matched the db value.
The revised function creates the element, but it's only adding the first value from the db. How can I modify it so that it will loop through all the values that should be added to the <select> element?
PHP Function and Query
<?php
function printSelectOptions($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . $value . '</option>';
}
}
try {
$stmt = $conn->prepare("SELECT * FROM student");
$stmt->execute();
}catch(PDOException $e) {
echo $e->getMessage();
}
$row = $stmt->fetch();
?>
Populate Select Element
<select name="fname">
<?php
echo printSelectOptions(array($row['fname']));
?>
</select>
The Original Function & Code for Populating an Element
function printSelectOptions($dataArray, $currentSelection) {
foreach ($dataArray as $key => $value) {
echo '<option ' . (($key == $currentSelection) ? 'selected="selected"' : '') . ' value="' . $key . '">' . $value . '</option>';
}
}
<select name="fname">
<?php
$options = array("John"=>"John", "Mary"=>"Mary", "Elizabeth"=>"Elizabeth");
$selected = $row['fname'];
echo printSelectOptions($options, $selected);
?>
</select>
Since you have only fetched a single row via fetch(), only a single value is getting passed into your function printSelectOptions(). Instead, get all rows via fetchAll()
and modify your function to receive the full array, plus a string which is the column name (array key) you want to print from.
// All rows into $rows...
$rows = $stmt->fetchAll();
// Make the function accept the full 2D array, and
// a string key which is the field name to list out:
function printSelectOptions($dataArray, $currentSelection, $fieldname) {
// String to hold output
$output = '';
foreach ($dataArray as $key => $value) {
// Rather than echo here, accumulate each option into the $output string
// Use the $fieldname as a key to $value which is now an array...
$output .= '<option ' . (($key == $currentSelection)) . ' value="' . $key . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
}
return $output;
}
Then call the function as:
echo printSelectOptions($rows, $currentSelection, 'fname');
The way it is right now, the option's value attribute is populated by the array key, which would be numbered from zero. That's similar to your original array version, but it might be more useful to specify another column name like id as the key column.
// This one also takes a $valuename to use in place of $key...
function printSelectOptions($dataArray, $currentSelection, $valuename, $fieldname) {
// String to hold output
$output = '';
foreach ($dataArray as $key => $value) {
// Rather than echo here, accumulate each option into the $output string
// Use the $fieldname as a key to $value which is now an array...
$output .= '<option ' . (($value[$valuename] == $currentSelection)) . ' value="' . $value[$valuename] . '">' . htmlspecialchars($value[$fieldname], ENT_QUOTES) . '</option>';
}
return $output;
}
And would be called as:
echo printSelectOptions($rows, $currentSelection, 'id', 'fname');

Categories