distribute array values in multiple select box - php

I have an array as follows
$myArray = array('a','b','c','d');
I need to distribute some values of them saved already in database into different number of select boxes let's say 4 list boxes so these saved values will appear selected in the first list boxes and the remaining ones will be default and let's say saved values are a and c
so based on that the output should have 4 list boxes starting with a (Selected) and second list box c (Selected) and the other 2 list boxes should be remained default something like that
<select id="id" name="id" class="form-control">
<option value="">No selection</option>
<option value="a" selected>a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<select id="id" name="id" class="form-control">
<option value="">No selection</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c" selected>c</option>
<option value="d">d</option>
</select>
<select id="id" name="id" class="form-control">
<option value="" selected>No selection</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
<select id="id" name="id" class="form-control">
<option value="" selected>No selection</option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>
Edit
Here is my code where i loop to produce either 7 or 9 list boxes according to the passed value and inside i loop on $municipals to show all municipals and a municipal exists inside an array of the saved values in DB i need to show it in the first select box and so on
<?php if(!empty($municipal_number->meta_value)):
$ids = array();
foreach($municipal_ids as $municipal_id) {
$ids[] = $municipal_id->meta_value;
}
if($municipal_number->meta_value == 7):
for ($x = 1; $x <= 7; $x++): ?>
<div class="col-lg-3">
<label>Select Municipal</label>
<select id="municipal_id_<?php echo $x; ?>" name="municipal_id[]" class="municipal_id form-control">
<option value="0" selected>No Municipal</option>
<?php foreach($municipals as $municipal): ?>
<?php if(in_array($municipal->id, $ids)): ?>
<option selected value="<?php echo $municipal->id; ?>"><?php echo $municipal->first_name.' '.$municipal->last_name; ?></option>
<?php else: ?>
<option value="<?php echo $municipal->id; ?>"><?php echo $municipal->first_name.' '.$municipal->last_name; ?></option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<?php endfor;
elseif($municipal_number->meta_value == 9):
for ($x = 1; $x <= 9; $x++): ?>
<div class="col-lg-3">
<label>Select Municipal</label>
<select id="municipal_id_<?php echo $x; ?>" name="municipal_id[]" class="municipal_id form-control">
<option value="0" selected>No Municipal</option>
<?php foreach($municipals as $municipal): ?>
<?php if(in_array($municipal->id, $ids)): ?>
<option value="<?php echo $municipal->id; ?>"><?php echo $municipal->first_name.' '.$municipal->last_name; ?></option>
<?php else: ?>
<option value="<?php echo $municipal->id; ?>"><?php echo $municipal->first_name.' '.$municipal->last_name; ?></option>
<?php endif; ?>
<?php endforeach; ?>
</select>
</div>
<?php endfor; ?>
<?php endif; ?>
<?php endif; ?>

Make use of array_shift() function and a simple for loop to implement your logic, like this:
$myArray = array('a','c');
for($i = 0; $i < 4; ++$i){
$flag = false;
?>
<select id="id" name="id" class="form-control">
<option value="">No selection</option>
<option value="a" <?php if(!$flag && in_array('a', $myArray)){ echo "selected='selected'"; $flag = true; } ?>>a</option>
<option value="b" <?php if(!$flag && in_array('b', $myArray)){ echo "selected='selected'"; $flag = true; } ?>>b</option>
<option value="c" <?php if(!$flag && in_array('c', $myArray)){ echo "selected='selected'"; $flag = true; } ?>>c</option>
<option value="d" <?php if(!$flag && in_array('d', $myArray)){ echo "selected='selected'"; $flag = true; } ?>>d</option>
</select>
<?php
array_shift($myArray);
}
Note: Take care of id and name attributes, it should be unique for every element.

Here's some sample code:
$myArray = array('a','b','c','d');
$selected_values = array('a','c');
$number_of_selects = 4;
for ($i = 0; $i < $number_of_selects; $i++) {
$sel_val = !empty($selected_values[$i])? $selected_values[$i] : false;?>
<select>
<?php
foreach ($myArray as $v) {?>
<option value="<?=$v?>" <?=$v===$sel_val? 'selected' : ''?>><?=$v?><option>
<?php
}?>
</select>
<?php
}

Related

How to display selected dropdown name in PHP [duplicate]

Consider:
<form method="get" action="">
<select name="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<select name="location">
<option value="x">x</option>
<option value="y">y</option>
</select>
<input type="submit" value="Submit" class="submit" />
</form>
On submitting the form, how do I make sure that the selected values remain selected in the dropdowns? This form is inside WordPress (PHP).
To avoid many if-else structures, let JavaScript do the trick automatically:
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
<select name="location" id="location">
<option value="x">x</option>
<option value="y">y</option>
</select>
<script type="text/javascript">
document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>
<select name="name">
<option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
<option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>
After trying all these "solutions", nothing work. I did some research on W3Schools before and remember there was explanation of keeping values about radio.
But it also works for the Select option. See below for an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
If you are using WordPress (as is the case with the OP), you can use the selected function.
<form method="get" action="">
<select name="name">
<option value="a" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'a' ); ?>>a</option>
<option value="b" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'b' ); ?>>b</option>
</select>
<select name="location">
<option value="x" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'x' ); ?>>x</option>
<option value="y" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'y' ); ?>>y</option>
</select>
<input type="submit" value="Submit" class="submit" />
</form>
Since WordPress already uses jQuery you can try something like this:
var POST=<?php echo json_encode($_POST); ?>;
for(k in POST){
$("#"+k).val(POST[k]);
}
JavaScript only solution:
var tmpParams = decodeURIComponent(window.location.search.substr(1)).split("&");
for (var i = 0; i < tmpParams.length; i++) {
var tmparr = tmpParams[i].split("=");
var tmp = document.getElementsByName(tmparr[0])[0];
if (!!tmp){
document.getElementsByName(tmparr[0])[0].value = tmparr[1];
}
}
Or if you are using jQuery you can replace
var tmp = document.getElementsByName(tmparr[0])[0];
if (!!tmp){
document.getElementsByName(tmparr[0])[0].value = tmparr[1];
}
with:
$('*[name="'+tmparr[0]+'"]').val(tmparr[1]);
Try this solution for keep selected value in dropdown:
<form action="<?php echo get_page_link(); ?>" method="post">
<select name="<?php echo $field_key['key']; ?>" onchange="javascript:
submit()">
<option value="">All Category</option>
<?php
foreach( $field['choices'] as $key => $value ){
if($post_key==$key){ ?>
<option value="<?php echo $key; ?>" selected><?php echo $value; ?></option>
<?php
}else{?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php }
}?>
</select>
</form>
This works for me!
<label for="reason">Reason:</label>
<select name="reason" size="1" id="name" >
<option value="NG" selected="SELECTED"><?php if (!(strcmp("NG", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>Selection a reason below</option>
<option value="General"<?php if (!(strcmp("General", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>General Question</option>
<option value="Account"<?php if (!(strcmp("Account", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Account Question</option>
<option value="Other"<?php if (!(strcmp("Other", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Other</option>
</select>
Just change this line:
<input type="submit" value="Submit" class="submit" />
with this line:
<input type="submit" value="Submit/Reload" class="submit" onclick="history.go(-1);">
I don't work in WordPress much, but for forms outside of WordPress, this works well.
PHP
location = ""; // Declare variable
if($_POST) {
if(!$_POST["location"]) {
$error .= "Location is required.<br />"; // If not selected, add string to error message
}else{
$location = $_POST["location"]; // If selected, assign to variable
}
HTML
<select name="location">
<option value="0">Choose...</option>
<option value="1" <?php if (isset($location) && $location == "1") echo "selected" ?>>location 1</option>
<option value="2" <?php if (isset($location) && $location == "2") echo "selected" ?>>location 2</option>
</select>
<select name="name">
<?php $options = ["a", "b", "c", "d", "e"];
foreach($options as $o){
if($o == $_GET['name']) $attr="selected='true'";
else $attr = "";
echo "<option value='{$o}' {$attr}>{$o}</option>";
}
?>
</select>
We can create an array of option before hand and only use simple if/else to check if selected or not. If you want different values for data and different value for displaying option you can use associative arrays too.
<select name="name">
<?php $options = ["a"=>"Option A", "b"=>"Option B", "c"=>"Option C", "d"=>"Option D", "e"=>"Option E"];
foreach($options as $index=>$o){
if($index == $_GET['name']) $attr="selected='true'";
else $attr = "";
echo "<option value='{$index}' {$attr}>{$o}</option>";
}
?>
</select>
<form method="get" action="">
<select name="name" value="<?php echo $_GET['name'];?>">
<option value="a">a</option>
<option value="b">b</option>
</select>
<select name="location" value="<?php echo $_GET['location'];?>">
<option value="x">x</option>
<option value="y">y</option>
</select>
<input type="submit" value="Submit" class="submit" />
</form>

how to show the selected value from database in select box in codeigniter

Here I have a select box where I want to show the value which is stored in the database that is in the JSON format. If the value is present, it shows the selected value, otherwise it shows the default option Delete leads option. It's not working properly.
<div class="col-md-7">
<select class="form-control" id="spm" name="spm" required style="">>
<option value=""> Delete Leads </option>
<?
foreach($slct_optn as $slct_optns)
{
$slctoptn = json_decode($slct_optns['spam_management'],1);
?>
<option value="7" <?php if($slctoptn['delete']==7) {?> selected="selected" <? } ?>>1 Week Older</option>
<option value="30" <?php if($slctoptn['delete']==30) {?> selected="selected" <? } ?>>1 Month</option>
<option value="60" <?php if($slctoptn['delete']==60) {?> selected="selected" <? } ?>>2 Month</option>
<? }
?>
</select>
Can anyone please help me?
I think you could change the $slctoptn['delete'] to $slctoptn[0]['delete'] variable like this :
<div class="col-md-7">
<select class="form-control" id="spm" name="spm" required style="">>
<option value=""> Delete Leads </option>
<?
foreach($slct_optn as $slct_optns)
{
$slctoptn = json_decode($slct_optns['spam_management'],1);
?>
<option value="7" <?php if($slctoptn[0]['delete']==7) {?> selected="selected" <? } ?>>1 Week Older</option>
<option value="30" <?php if($slctoptn[0]['delete']==30) {?> selected="selected" <? } ?>>1 Month</option>
<option value="60" <?php if($slctoptn[0]['delete']==60) {?> selected="selected" <? } ?>>2 Month</option>
<? }
?>
</select>
This will use the only 'delete' array inside the $slctoptn parent array.

Drop-down list in HTML with options based on php rows

I want to make a dropdown list based on options that are obtained from an MySQL database. At this moment my code looks like this:
<?php
if ($resultCheck12 > 0) {
while ($row = mysqli_fetch_assoc($result12)) { ?>
<select name="storage_location[]" required>
<option value=""></option>
<option value="<?php echo $row['id']; ?>"><?php echo $row['storage_name']; ?></option>
</select>
<?php } } ?>
And this code should produce a result that looks like this if it was unsystematically coded:
<select name="sample_group[]" class="sample_group" required>
<option value=""></option>
<option value="water">Water</option>
<option value="pharmaceutical">Pharmaceutical</option>
<option value="food">Food</option>
<option value="food">Swabs</option>
<option value="custom">Custom</option>
</select>
However the results produce something like this:
<select name="sample_group[]" class="sample_group" required>
<option value=""></option>
<option value="water">Water</option>
</select>
<select name="sample_group[]" class="sample_group" required>
<option value=""></option>
<option value="pharmaceutical">Pharmaceutical</option>
</select>
<select name="sample_group[]" class="sample_group" required>
<option value=""></option>
<option value="food">Food</option>
</select>
<select name="sample_group[]" class="sample_group" required>
<option value=""></option>
<option value="swabs">Swabs</option>
</select>
<select name="sample_group[]" class="sample_group" required>
<option value=""></option>
<option value="custom">Custom</option>
</select>
Instead of producing a single dropdown list it makes one for each variable from the MySQL database.
Any ideas how to resolve this issue?
<?php
if ($resultCheck12 > 0) { ?>
<select name="storage_location[]" required>
<option value=""></option>
<?php while ($row = mysqli_fetch_assoc($result12)) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['storage_name']; ?></option>
<?php } ?>
</select>
<?php } ?>
The select tag should be outside the while loop
You are using select tag inside while loop that's why it is repeating it multiple times.
<?php if ($resultCheck12 > 0) { ?>
<select name="storage_location[]" required>
<option value=""></option>
<?php while ($row = mysqli_fetch_assoc($result12)) { ?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['storage_name']; ?></option>
<?php } ?>
</select>
<?php } ?>

How to retain Select option after submitting the form in php

I looked at several community forums, and I am unable to figure it out on how to retain select option value after validation fails.
Here is the code that works for me, but values disappear when submit button is submitted.
<select id="service" name="service" class="searchoption">
<option value="">-- Select Service Name --</option>
<?php
$resultservice = mysqli_query($con,"Select * from services") ?>
<?php
while ($line = mysqli_fetch_array($resultservice)) {
?>
<option value="<?php echo $line['serviceid'];?>"> <?php echo $line['service'];?> </option>
<?php
}
?>
</select>
Here is what I tried and doesn't work for me:
<select id="service" name="service" class="searchoption">
<option value="">-- Select Service Name --</option>
<?php
$resultservice = mysqli_query($con,"Select * from services") ?>
<?php
while ($line = mysqli_fetch_array($resultservice)) {
?>
<option value="<?php echo $line['serviceid']; if ($_POST['service'] == $service) {echo 'selected="selected"'} echo $line['serviceid']; ?>"> <?php echo $line['service'];?> </option>
<?php
}
?>
</select>
<form action="" method="POST">
<select name="list" id="list">
<option value="item1">item1</option>
<option value="item2">item2</option>
<option value="item3">item3</option>
</select>
<input type="submit" />
</form>
<script type="text/javascript">
document.getElementById('list').value = "<?php echo $_POST['list']?>";
</script>
May be a small error but noticed a invalid > in the following code
<option value="<?php echo $line['serviceid']; if ($_POST['service'] == $service) {echo 'selected="selected"'} echo $line['serviceid']; ?>"> <?php echo $line['service'];?> </option>
Try this
<option value="<?php echo $line['serviceid']; if ($_POST['service'] == $service) {echo 'selected="selected"'}?> echo $line['serviceid']; <?php echo $line['service'];?>" </option>
hope this helps

Keep values selected after form submission

Consider:
<form method="get" action="">
<select name="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<select name="location">
<option value="x">x</option>
<option value="y">y</option>
</select>
<input type="submit" value="Submit" class="submit" />
</form>
On submitting the form, how do I make sure that the selected values remain selected in the dropdowns? This form is inside WordPress (PHP).
To avoid many if-else structures, let JavaScript do the trick automatically:
<select name="name" id="name">
<option value="a">a</option>
<option value="b">b</option>
</select>
<script type="text/javascript">
document.getElementById('name').value = "<?php echo $_GET['name'];?>";
</script>
<select name="location" id="location">
<option value="x">x</option>
<option value="y">y</option>
</select>
<script type="text/javascript">
document.getElementById('location').value = "<?php echo $_GET['location'];?>";
</script>
<select name="name">
<option <?php if ($_GET['name'] == 'a') { ?>selected="true" <?php }; ?>value="a">a</option>
<option <?php if ($_GET['name'] == 'b') { ?>selected="true" <?php }; ?>value="b">b</option>
</select>
After trying all these "solutions", nothing work. I did some research on W3Schools before and remember there was explanation of keeping values about radio.
But it also works for the Select option. See below for an example. Just try it out and play with it.
<?php
$example = $_POST["example"];
?>
<form method="post">
<select name="example">
<option <?php if (isset($example) && $example=="a") echo "selected";?>>a</option>
<option <?php if (isset($example) && $example=="b") echo "selected";?>>b</option>
<option <?php if (isset($example) && $example=="c") echo "selected";?>>c</option>
</select>
<input type="submit" name="submit" value="submit" />
</form>
If you are using WordPress (as is the case with the OP), you can use the selected function.
<form method="get" action="">
<select name="name">
<option value="a" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'a' ); ?>>a</option>
<option value="b" <?php selected( isset($_POST['name']) ? $_POST['name'] : '', 'b' ); ?>>b</option>
</select>
<select name="location">
<option value="x" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'x' ); ?>>x</option>
<option value="y" <?php selected( isset($_POST['location']) ? $_POST['location'] : '', 'y' ); ?>>y</option>
</select>
<input type="submit" value="Submit" class="submit" />
</form>
Since WordPress already uses jQuery you can try something like this:
var POST=<?php echo json_encode($_POST); ?>;
for(k in POST){
$("#"+k).val(POST[k]);
}
JavaScript only solution:
var tmpParams = decodeURIComponent(window.location.search.substr(1)).split("&");
for (var i = 0; i < tmpParams.length; i++) {
var tmparr = tmpParams[i].split("=");
var tmp = document.getElementsByName(tmparr[0])[0];
if (!!tmp){
document.getElementsByName(tmparr[0])[0].value = tmparr[1];
}
}
Or if you are using jQuery you can replace
var tmp = document.getElementsByName(tmparr[0])[0];
if (!!tmp){
document.getElementsByName(tmparr[0])[0].value = tmparr[1];
}
with:
$('*[name="'+tmparr[0]+'"]').val(tmparr[1]);
Try this solution for keep selected value in dropdown:
<form action="<?php echo get_page_link(); ?>" method="post">
<select name="<?php echo $field_key['key']; ?>" onchange="javascript:
submit()">
<option value="">All Category</option>
<?php
foreach( $field['choices'] as $key => $value ){
if($post_key==$key){ ?>
<option value="<?php echo $key; ?>" selected><?php echo $value; ?></option>
<?php
}else{?>
<option value="<?php echo $key; ?>"><?php echo $value; ?></option>
<?php }
}?>
</select>
</form>
This works for me!
<label for="reason">Reason:</label>
<select name="reason" size="1" id="name" >
<option value="NG" selected="SELECTED"><?php if (!(strcmp("NG", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>Selection a reason below</option>
<option value="General"<?php if (!(strcmp("General", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>General Question</option>
<option value="Account"<?php if (!(strcmp("Account", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Account Question</option>
<option value="Other"<?php if (!(strcmp("Other", $_POST["reason"]))) {echo "selected=\"selected\"";} ?>>Other</option>
</select>
Just change this line:
<input type="submit" value="Submit" class="submit" />
with this line:
<input type="submit" value="Submit/Reload" class="submit" onclick="history.go(-1);">
I don't work in WordPress much, but for forms outside of WordPress, this works well.
PHP
location = ""; // Declare variable
if($_POST) {
if(!$_POST["location"]) {
$error .= "Location is required.<br />"; // If not selected, add string to error message
}else{
$location = $_POST["location"]; // If selected, assign to variable
}
HTML
<select name="location">
<option value="0">Choose...</option>
<option value="1" <?php if (isset($location) && $location == "1") echo "selected" ?>>location 1</option>
<option value="2" <?php if (isset($location) && $location == "2") echo "selected" ?>>location 2</option>
</select>
<select name="name">
<?php $options = ["a", "b", "c", "d", "e"];
foreach($options as $o){
if($o == $_GET['name']) $attr="selected='true'";
else $attr = "";
echo "<option value='{$o}' {$attr}>{$o}</option>";
}
?>
</select>
We can create an array of option before hand and only use simple if/else to check if selected or not. If you want different values for data and different value for displaying option you can use associative arrays too.
<select name="name">
<?php $options = ["a"=>"Option A", "b"=>"Option B", "c"=>"Option C", "d"=>"Option D", "e"=>"Option E"];
foreach($options as $index=>$o){
if($index == $_GET['name']) $attr="selected='true'";
else $attr = "";
echo "<option value='{$index}' {$attr}>{$o}</option>";
}
?>
</select>
<form method="get" action="">
<select name="name" value="<?php echo $_GET['name'];?>">
<option value="a">a</option>
<option value="b">b</option>
</select>
<select name="location" value="<?php echo $_GET['location'];?>">
<option value="x">x</option>
<option value="y">y</option>
</select>
<input type="submit" value="Submit" class="submit" />
</form>

Categories