Drop down - show previously selected in loop - php

my problem is to show previously selected in a while loop. I found a way to do it in not-loop setup, but a loop is a problem for me.
The following code give me a drop down of countries (and country code):
<?php
foreach($countries as $key => $value) { ?>
<option value="<?= $value . ' ' . $key ?>" title="<?= htmlspecialchars($value) ?>"><?= htmlspecialchars($value) ?></option>
<?php } ?>
And it works good. But imagine someone edit their country, thus I would love to show previously selected country. Of course I have a variable with the specific previously selected country... Thanks.

<?php
$preselected = 'whatever_previous_selected';
foreach($countries as $key => $value) { ?>
<option value="<?php $value; ?>" title="<?= htmlspecialchars($value) ?>" <?php if($preselected == $value) {echo "selected='selected'"; }?>>
<?= htmlspecialchars($value) ?>
</option>
<?php } ?>

try this:
<?php
foreach($countries as $key => $value) { ?>
<?php if ($previousCountry == $value) ?>
<option selected value="<?= $value . ' ' . $key ?>" title="<?= htmlspecialchars($value) ?>"><?= htmlspecialchars($value) ?></option>
<?php else ?>
<option value="<?= $value . ' ' . $key ?>" title="<?= htmlspecialchars($value) ?>"><?= htmlspecialchars($value) ?></option>>
<?php } ?>
Not sure with the syntax but you should detect if the value is equal to the previous country then you put selected attribute on it.

Use selected='selected' when you get id in edit.
<?php
$id = 1; // In edit you get some value here
foreach($countries as $key => $value) {
$selected = (isset($id) && $id == $key) ? "selected='selected'" : "";
?>
<option value="<?= $value . ' ' . $key ?>" title="<?= htmlspecialchars($value) ?>" <?php echo $selected ?>><?= htmlspecialchars($value) ?></option>
<?php } ?>

try this:
<?php
$prevSelectedCountry;
foreach($countries as $key => $value) { ?>
<option <?php echo ($prevSelectedCountry == $value . ' ' . $key)?"selected='selected'":"" ?> value="<?= $value . ' ' . $key ?>" title="<?= htmlspecialchars($value) ?>"><?= htmlspecialchars($value) ?></option>
<?php } ?>

Related

How to Use Dynamic Dropdown Selected value in Php

Php/Html:
Here I add The all Countries list to add/edit page.But Edit page Want Value Selected in dropdown.please help
<select class="form-control" id="country_list" name="country">
<?php
global $wpdb;
$network_lists = $wpdb->get_results("SELECT * FROM media_countries");
foreach($network_lists as $network_list){
?>
<option value="<?php echo $network_list->country_name ?>" selected="<?php
echo $network_list->country_name ?>"><?php echo $network_list>country_name ?></option>
<?php }?>
</select>
This is how I would do it. This will check the value against the value the user selects with the value from the database and properly populate your dropdown menu.
global $wpdb;
$network_lists = $wpdb->get_results("SELECT * FROM media_countries");
echo
'<select class="form-control" id="country_list" name="country">';
foreach($network_lists as $network_list) {
if($_POST['country'] == $network_list->country_name) {
echo '<option value="' . $network_list->country_name . '"' . ' selected="selected"' . '>' . $network_list->country_name . '</option>';
}else {
echo '<option value="' . $network_list->country_name . '">' . $network_list->country_name . '</option>';
}
}
echo
'</select>';
Selected value is in $_POST['country'];
Try:
<select class="form-control" id="country_list" name="country">
<?php
global $wpdb;
$network_lists = $wpdb->get_results("SELECT * FROM media_countries");
foreach($network_lists as $network_list){
?>
<option value="<?php echo $network_list->country_name; ?>" <?php echo ( $_POST['country_name'] == $network_list->country_name ? 'selected' : '' ); ?>><?php echo $network_list>country_name; ?></option>
<?php }?>
</select>
The above code automatically selects the option that has value equals to the submitted $_POST['country'] value.

PHP decode JSON into selectmenu selected options

I want to get the options selected, i tried many ways and when i select an option from the list and after pressing submit the selectmenu points to the first element, which makes the option that i selected not actually selected. And i can't send what the user have chosen.
<?php
$operatorsAndPackages = $_SESSION['outputOperatorsAndPackages'];
$json_a = json_decode($operatorsAndPackages,true);
?>
<label>Paquet : Opérateur : Montant</label><br/>
<select id="recharge_operator" name="recharge_operator">
<?php foreach ($json_a as $value): ?>
<?php echo $value; ?>
<option value="<?php echo $value[paquet_id] . ":" . $value[code_operateur] . ":" . $value[montant_recharge]; ?>"><?php echo $value[paquet_id] . ":" . $value[code_operateur] . ":" . $value[montant_recharge]; ?></option>
<?php endforeach ?>
</select>
You need to look at the submitted value (I'll assume this is a POST operation in my code sample) and compare it to each assembled value in the loop to determine if the current is the same as what was submitted. If it is, you set the selected attribute of your option element.
Lines 13 and 16 of the following code sample are the most pertinent changes.
<?php
$operatorsAndPackages = $_SESSION['outputOperatorsAndPackages'];
$json_a = json_decode($operatorsAndPackages,true);
?>
<label>Paquet : Opérateur : Montant</label><br/>
<select id="recharge_operator" name="recharge_operator">
<?php
foreach ($json_a as $value)
{
$value = $value['paquet_id'] . ":" . $value['code_operateur'] . ":" . $value['montant_recharge'];
$selected = ($value === $_GET['recharge_operator']);
$html_safe_value = htmlentities($value);
?>
<option value="<?php echo $html_safe_value; ?>"<?php if ($selected) {?> selected="selected"<?php } ?> >
<?php echo $html_safe_value; ?>
</option>
<?php
}
?>
</select>
I have a quick demo with source code available at: http://jaaulde.com/test_bed/SO_Lotus91/

Php option value

I have a list of areas (1000+) and i was wondering if there was a way i can do this easier with code instead of repeating each value.
<select>
<option value="apple" <?php if ($user_data["$area"] == apple){echo 'selected';} ?>>Apple
</option>
<option value="lemon" <?php if ($user_data["$area"] == lemon){echo 'selected';} ?>>Lemon
</option>
<option value="orange" <?php if ($user_data["$area"] == orange){echo 'selected';} ?>>Orange
</option>
<option value="banana" <?php if ($user_data["$area"] == banana){echo 'selected';} ?>>Banana
</option>
</select>
I.E. have the same piece of php code for each option instead of having to type in the name of the value each time
<?php if ($user_data["$area"] == option VALUE){echo 'selected';} ?>
Could you provide some code or ideas for what to look in tutorials, i have no idea how to start. Thank you!
//pseudo
$arr = array("apple", "lemon", "orange", ...);
foreach($arr as $value) {
echo '<option value="'.$value;
if($user_data[$area] === $value) {
echo 'selected';
}
//echo {the end of your option field syntax}
}
All the solutions look good... Here's one more way though:
<select>
<?php
$areas = array('apple', 'lemon', 'orange', 'banana');
$areas_count = count($areas);
for ($i = 0; $i < $areas_count; $i++) {
echo '<option value="' . $areas[$i] . '"';
echo ($user_data[$area] == $areas[$i]) ? ' selected' : '';
echo '>' . ucwords($areas[$i]) . '</option>';
}
?>
</select>
Use an array:
$areas = array(
'apple' => 'Apple',
'lemon' => 'Lemon',
'orange' => 'Orange',
'banana' => 'Banana'
);
Then use that array to print the select:
<select>
<?php foreach ($areas as $value => $text): ?>
<option value="<?php echo $value; ?>" <?php if ($user_data[$area] == $value) {echo 'selected';} ?>><?php echo $text; ?>
</option>
<?php endforeach; ?>
</select>
I am using an associative array because I am assuming that you want to be able to customize the areas' text label, and that they will not only be a capitaized version of the value used to match the user data.
foreach ($areas as $key => $val)
{
$select.= '<option '; // opening the option tag
foreach ($selected_from_db as $keyselected => $valselected)
{
$val_fetch_from_array = $valselected == $val['campaignid'] ? 'selected' : '';
$select.= $val_fetch_from_array; // codes for selecting multiple values
}
$select.= ' value = "' . $val['campaignid'] . '">#' . $val['campaignid'] . '-' . $val['campaignname'] . '</option>'; // closing the option tag
}

Foreach php function inside HTML select options

Im a newbie to this forum and have just started coding in php. Need some help. I have the following code
<?php error_reporting(-1);
require_once('/mysql/sql_connect.php');
$q = "SELECT pty.pty_profile_name AS profile FROM pty, users WHERE users.username = 'testaccount' ";
$r = #mysqli_query ($dbc, $q);
$results_array = array();
while($row = mysqli_fetch_assoc($r)) {
array_push($results_array, $row);
echo "<pre>"; print_r($results_array); echo "</pre>"; }
?>
<p>
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
<input type="submit" name="Submit" />
</form>
<?php
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
The output I get is correct, but it displays the key, eg, 0 or 1 or 2, based on what I select in the form. I need the value output. Eg 0 = Emerton, it outputs "0" instead of Emerton.
If I echo $value['profile'] instead of pty_select, I get the last result of the query all the time. Which in this example would be 2, which is Ambarvale as I believe it just chooses the last row output of the query.
I hope I've made sense. Thanks in advance.
It will obviously echo the key, as you assigned the value of options as $key
if you need the options in the $_POST['pty_select'] use this:
<select name="pty_select" >
<?php foreach($results_array as $key => $value){ ?>
<option value="<?php echo $value['profile'];?>"><?php echo $value['profile']; ?></option>
<?php } ?>
</select>
You mean you need the value what you have used to display it.
Then,
Change to :
<option value="<?php echo $value['profile']; ?>">
<?php echo $value['profile']; ?>
</option>
And now let's go to ideal world :)
Build data pairs database_id => name for options:
$q = "SELECT pty.id, pty.pty_profile_name AS profile FROM pty, users
WHERE users.username = 'testaccount'";
$r = mysqli_query($dbc, $q);
$values = array();
while($r = mysqli_fetch_row($r)) {
$values[$r[0]] = $r[1];
}
Never use # when working with database, why do you want to suppress errors instead of preventing/handling them?
Now you have real database IDs and respective values (in general, using unique IDs are better... if nothing else they have greater entropy - more efficient search). And sice displaying select box is really common in webs, lets:
function selectbox( $values = array(), $attributes = array(), $selected_value = null)
{
// Header
echo '<select';
foreach( $attributes as $key => $val){
echo ' ' . htmlspecialchars($key) . '="' . htmlspecialchars( $val) . '"';
}
echo '>';
// Values
foreach( $values as $key => $val){
echo '<option value="' . htmlspecialchars( $key) .'"';
if( $key === $selected_value){
echo ' selected="selected"';
}
echo '>' . htmlspecialchars( $val) . '</option>';
}
echo '</select>';
}
And now usage :)
<form method="post" action="foreach2.php">
<label for="Property Select" class="title">Select Property</label>
<?php selectbox( $values, array( 'name' => 'pty_select')); ?>
<input type="submit" name="Submit" />
</form>
And what to do with it then?
$id = (int)(isset( $_POST['pty_select']) ? $_POST['pty_select'] : 0);
$name = null;
if( $id && isset( $values[$id])){
$name = $values[$id];
}
Give
<option value="<?php echo $value['profile']; ?>"><?php echo $value['profile']; ?></option>
instead of
<option value="<?php echo $key; ?>"><?php echo $value['profile']; ?></option>
if (isset($_POST['Submit'])) {
echo "<pre>"; echo ($_POST['pty_select']); echo "</pre>"; } ?>
Change it to something like
if(isset($_POST['Submit'])) {
echo $results_array[$_POST['pty_select']]['profile'];
}
Or alternatively use profile option value.

Multiple Select with Explode: only returns the word "Array"

Using Wordpress I have created a multiple select box so that users can select categories to exclude. When the page initially loads I see my default values pre-selected. However when I select new values and save... I only see the word "Array" echoed and nothing selected?
<select class="amultiple" id="<?php echo $value['id']; ?>" name="<?php echo $value['id']; ?>[]" multiple="multiple" size="8">
<?php
global $options;
foreach ($options as $value) {
if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] );
}
}
$categories = &get_categories('type=post&orderby=name&hide_empty=1');
if ($categories) {
$ex_cat = implode(',', $tt_cat_exclude);
foreach ($categories as $category) {
$selected = (in_array($ex_cat, $category->cat_ID)) ? ' selected="selected"' : '';
echo '<option value="' . $category->cat_ID . '"' . $selected . '>' . $category->cat_name . '</option>' . "\n";
}
}
?>
</select>
<br />For testing purposes, print variables: <?php echo $ex_cat; ?>
http://i48.tinypic.com/k9e3qq.gif
You should use implode()
Like so
$ex_cat = implode(',', $tt_cat_exclude);
This will return a comma separated list
This line should be
$selected = (in_array($category->cat_ID, $ex_cat)) ? ' selected="selected"' : '';
Changed to
$selected = (in_array($category->cat_ID, $tt_cat_exclude)) ? ' selected="selected"' : '';
Since the $ex_cat is a string and cannot be used in in_array()
The $ex_cat is now redundant i guess.
Looks like tt_cat_exclude is missing it's opening $
name="tt_cat_exclude[]" means you're defining an array, so it's normal for the output to be "array"
for testing try print_r (outputs the whole architecture of the variable)
or var_dump (outputs the var type too)
When you postback, the field tt_cat_exclude is an array of the values that you've set - because you've name it tt_cat_exclude[] with a [] behind.
Example:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<select class="amultiple" id="tt_cat_exclude" name="tt_cat_exclude[]" multiple="multiple" size="8">
<option value="1">TestingA</option>
<option value="2">TestingB</option>
<option value="3">TestingC</option>
<option value="4">TestingD</option>
<option value="5">TestingE</option>
</select>
<input type="submit" value="Submit" />
</form>
<br/><br/>For testing purposes: <?php
if(isset($_POST['tt_cat_exclude'])){
var_dump($_POST['tt_cat_exclude']); // outputs an array of the selected values
}
?>

Categories