My code contains a select box for selecting multiple options.
<select name="menu-item-visibility[<?php echo $item_id; ?>][]" id="edit-menu-item-visibility-<?php echo $item_id; ?>" class="chzn-select" multiple="true"
<option value="AF" <?php $val = get_post_meta( $item_id, 'locations', true ); if ( is_array( $val ) ) { if ( in_array( "AF", $val ) ) { echo "selected='selected'"; } else { echo ""; } } ?> >Afghanistan</option>
<option value="AL" <?php $val = get_post_meta( $item_id, 'locations', true ); if ( is_array( $val ) ) { if ( in_array( "AL", $val ) ) { echo "selected='selected'"; } else { echo ""; } } ?> >Albania</option>
...
</select>
The problem is I'm writing the same code over and over and the select box alone makes up more than 50% of the lines of code. Seems kind of wasteful. I'm wondering if I can apply some abstraction by looping through an array of the countries stored in a separate file.
$countries = array (
'AF' => 'Afghanistan',
'AL' => 'Albania',
...
)
Any insight into how this might be accomplished in this case?
You can try -
<select name="menu-item-visibility[<?php echo $item_id; ?>][]" id="edit-menu-item-visibility-<?php echo $item_id; ?>" class="chzn-select" multiple="true"
<?php
$vals = get_post_meta( $item_id, 'locations', true );
foreach($countries as $key => $value) { // Loop through countries
?>
<option value="<?php echo $key;?>"
<?php echo (is_array( $vals ) && in_array( $key, $vals )) ? 'selected' : ''; ?> >
<?php echo $value;?>
</option>
<?php
}
?>
</select>
Also you can do like this, Its different from your code
<?php
$countries = ['de' => 'Germany','pl' => 'Poland','fr' => 'France'];
echo "<select>";
echo "<option value=''>Select Country</option>";
$country = "pl";
foreach ($countries as $code => $name) {
echo '<option value="' . $code . '" ' . ($country == $code ? 'selected="selected"' : null) . '>' . $name . '</option>';
}
echo "</select>";
?>
Related
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 } ?>
im new to PHP and im trying this stuff for hours, I wanted to show the Array items to the Select Option. Here's the code:
<select name="state">
<?php
$arrstate=array
(
array("AK","Alaska"),
array("AL","Alabama"),
array("AR","Arkansas"),
array("AZ","Arizona"),
array("CA","California"),
array("CO","Colorado"),
array("CT","Connecticut"),
array("DC","District of Columbia"),
array("DE","Delaware"),
array("FL","Florida"),
array("GA","Georgia"),
array("HI","Hawaii"),
array("IA","Iowa"),
array("ID","Idaho"),
array("IL","Illinois"),
array("IN","Indiana"),
array("KS","Kansas"),
array("KY","Kentucky"),
);
for($lop=0;$lop<=49;$lop++)
{
if (strtoupper($lead_info['state'])==$arrstate[$lop][0])
{
echo "<option selected=\"selected\" value=\"".$arrstate[$lop][0]."\">".$arrstate[$lop][1]."</option>\n";
}else{
echo "<option value=\"".$arrstate[$lop][0]."\">".$arrstate[$lop][1]."</option>\n";
}
}
?>
</select>
But it seems it only shows ".$arrstate[$lop][1]."
What seems to be the problem?
try it
<?php
$arrstate = array
(
'AK' => 'Alaska',
'AL' => 'Alabama',
'AR' => 'Arkansas',
'AZ' => 'Arizona'
); ?>
<select>
<?php foreach($arrstate as $key => $value) { ?>
<option value="<?php echo $key; ?>" <?=($value == $current_zip_entered ? "selected" : "" )?>><?php echo $value; ?></option>
<?php } ?></select>
<?php
$arrstate=array
(
"AK","Alaska",
"AL","Alabama",
"AR","Arkansas",
"AZ","Arizona"
);
?>
this is the easiest way...
<select>
<?php
foreach($arrstate as $key => $value) {
?>
<option value="<?php echo $key; ?>" <?=($value == $current_zip_entered ? "selected" : "" )?>><?php echo $value; ?></option>
<?php
}
?>
</select>
You can retrieve from database like this example:
<select>
<?php $result = mysqli_query($conn, "SELECT * FROM categories");
while ($row = mysqli_fetch_array($result)) {
$categories = array($row["category"]);
$arrlength = count($categories);
for($x = 0; $x < $arrlength; $x++) {
echo "<option>";
echo $categories[$x];
echo "</option>";
}}?>
</select>
I'm trying to add selected in option when condition true. Its working fine, but its giving two times selected.
foreach ($sorts as $sorts) {
if ($cat_id == 59 && $sorts['value'] == 'p.price-ASC') { // True if category id equal to 59
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
}else{
if ($sorts['value'] == $sort . '-' . $order) { // True if values are equal
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
}else {
<option value="<?php echo $sorts['href']; ?>"><?php echo $sorts['text']; ?></option>
}
}
}
In above you can see there are two conditions for selected.
True if category id equal to 59 if ($cat_id == 59 &&
$sorts['value'] == 'p.price-ASC')
True if values are equal if ($sorts['value'] == $sort . '-' .
$order)
On other category pages it totally working fine, but on category 59 two if statements are giving true. That's why on this page two selected are adding on two option.
<option value="name-az" >Name (A - Z)</option>
<option value="name-az" selected="selected">Name (Z - A)</option>
<option value="p.price-ASC" selected="selected">Price (Low > High)</option>
So can any one guide me how to fix or modify the condition that i can get only one true condition in one time. Thanks
You could solve it by using a new variable $done indicating that the selected value was added already:
$done = false;
foreach ($sorts as $sorts) {
if (!$done && $cat_id == 59 && $sorts['value'] == 'p.price-ASC') { // True if category id equal to 59
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
$done = true;
}else{
if (!$done && $sorts['value'] == $sort . '-' . $order) { // True if values are equal
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
$done = true;
}else {
<option value="<?php echo $sorts['href']; ?>"><?php echo $sorts['text']; ?></option>
}
}
}
Problem with the above and your code is that the foreach is incorrect. $sorts as $sorts is not possible for the foreach. I've refactored your code to more safe and better usable code. This code is also tested and works as expected:
//INPUT:
$sort = 'name';
$order = 'za';
$cat_id = 59;
$sorts = array(
'name-az' => 'Name (A - Z)',
'name-za' => 'Name (Z - A)',
'p.price-ASC' => 'Price (Low > High)',
'p.price-DESC' => 'Price (High > Low)'
);
//CODE:
if(!array_key_exists($sort . '-' . $order, $sorts)) //check your input!
throw new Exception('Invalid sort order.');
$selected = $cat_id == 59 ? 'p.price-ASC' : $sort . '-' . $order;
$done = false;
echo '<select>';
foreach ($sorts as $key => $value) {
echo '<option value="'.htmlentities($key, ENT_QUOTES, 'UTF-8').'"'.($selected==$key?' selected="selected"':'').'>'.htmlentities($value, ENT_QUOTES, 'UTF-8').'</option>';
}
echo '</select>';
Why use 2 if statements? That's what elseif is for. Does this code work for you?
foreach($sorts as $sorts)
{
if($cat_id == 59 && $sorts['value'] == 'p.price-ASC')
{
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
continue;
}
elseif($sorts['value'] == $sort . '-' . $order)
{
<option value="<?php echo $sorts['href']; ?>" selected="selected"><?php echo $sorts['text']; ?></option>
continue;
}
else
{
<option value="<?php echo $sorts['href']; ?>"><?php echo $sorts['text']; ?></option>
}
}
I need to echo the selected value first in a form when user wants to make an update. I tried several variants:
1)
<?php
$opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
echo '<select name="up_opt" >' ;
foreach ($opt as $i => $value) {
echo "<option value=\"$i\"";
if ($_REQUEST['up_opt'] == $i)
{
echo "selected" ;
}
echo ">$opt[$i]</option>" ;
}
echo '</select>' ;
?>
2)
<?php $opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
$edu = $_REQUEST['edu'];
<select name="up_opt">
<?php foreach ( $opt as $i=>$opt ) : ?>
<option value="<?php echo $i?>" <?php echo $i == $edu ? 'selected' : ''?>><?php echo $opt ?></option>
<?php endforeach; ?>
</select>
3)
<select name="up_opt">
<option value="1" <?php if ($_GET['1'] == 'option1') { echo 'selected'; } ?>>Opt1</option>
<option value="2" <?php if ($_GET['2'] == 'option2') { echo 'selected'; } ?>>Opt2</option>
<option value="3" <?php if ($_GET['3'] == 'option3') { echo 'selected'; } ?>>Opt3</option>
</select>
None of these variants echoes the checked value first. Can someone help me, tell me what is wrong or give me another variant?
Variant 3 is ok (but I'd rather use a loop instead of hard-coded options). Your mistake is that you compare 'option1', 'option2' and so one when your real values are '1', '2', '3'. Also as #ElefantPhace said, don't forget about spaces before selected, or you'll get invalid html instead. So it would be this:
<select name="up_opt">
<option value="1" <?php if ($_GET['up_opt'] == 1) { echo ' selected="selected"'; } ?>>Opt1</option>
<option value="2" <?php if ($_GET['up_opt'] == 2) { echo ' selected="selected"'; } ?>>Opt2</option>
<option value="3" <?php if ($_GET['up_opt'] == 3) { echo ' selected="selected"'; } ?>>Opt3</option>
</select>
With loop:
<?php
$options = array(
1 => 'Opt1',
2 => 'Opt2',
3 => 'Opt3',
);
?>
<select name="up_opt">
<?php foreach ($options as $value => $label): ?>
<option value="<?php echo $value; ?>" <?php if ($_GET['up_opt'] == 1) { echo ' selected="selected"'; } ?>><?php echo $label; ?></option>
<?php endforeach ?>
</select>
Here is all three of your variants, tested and working as expected. They are all basically the same, you were just using the wrong variable names, and different ones from example to example
1)
<?php
$opt= array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3') ;
echo '<select name="up_opt">';
foreach ($opt as $i => $value) {
echo "<option value=\"$i\"";
if ($_POST['up_opt'] == $i){
echo " selected";
}
echo ">$value</option>";
}
echo '</select>';
?>
2) uses same array as above
$edu = $_POST['up_opt'];
echo '<select name="up_opt">';
foreach ( $opt as $i => $value ){
echo "<option value=\"$i\"", ($i == $edu) ? ' selected' : '';
echo ">$value</option>";
}
echo "</select>";
3)
echo '<select name="up_opt">';
echo '<option value="1"', ($_POST['up_opt'] == '1') ? 'selected':'' ,'>Opt1</option>';
echo '<option value="2"', ($_POST['up_opt'] == '2') ? 'selected':'' ,'>Opt2</option>';
echo '<option value="3"', ($_POST['up_opt'] == '3') ? 'selected':'' ,'>Opt3</option>';
echo '</select>';
I have the following html:
<form action="" method="get">
<ul>
<li>location
<select name="locationdo">
<option value="tax_cb">Checkbox</option>
<option value="tax_radio">Radio</option>
<option value="tax_dd">Dropdown</option>
</select>
</li>
<li>genre
<select name="genredo">
<option value="tax_cb">Checkbox</option>
<option value="tax_radio">Radio</option>
<option value="tax_dd">Dropdown</option>
</select>
</li>
<li>studio
<select name="studiodo">
<option value="tax_cb">Checkbox</option>
<option value="tax_radio">Radio</option>
<option value="tax_dd">Dropdown</option>
</select>
</li>
</ul>
<p><input type="submit" value="submit" name="submit" /></p>
</form>
What I want is to have array elements from $which_tax_array stored in separate variables based on choices that were made. Hopefully the code will explain better what I want to achive (but it doesn't work as I wanted it to):
if (isset($_GET['submit'])) {
$which_tax_array = array('location', 'genre', 'studio');
$what = array();
foreach ($which_tax_array as $key => $tax_name) {
$what[$tax_name] = $_GET[$tax_name.'do'];
foreach ($what as $tax_term => $display_option) {
if ( in_array($what[$tax_name], $what) ) {
$checkboxes = ','.$tax_term;
} elseif ( in_array($what[$tax_name], $what) ) {
$radios .= ','.$tax_term;;
} elseif ( in_array($what[$tax_name], $what) ) {
$dropdowns .= ','.$tax_term;
}
}
}
}
echo 'cb '.$checkboxes.'<br>';
echo 'radio '.$radios . '<br>';
echo 'dd '.$dropdowns.'<br>';
Not sure what you are trying to do. I see a few possible issues -
(1) you are not closing your foreach ($which_tax_array as $key => $tax_name) until the end, so you are executing your next foreach too early.
(2) you have $checkboxes = ','.$tax_term; instead of $checkboxes .= ','.$tax_term; so you are overwriting your $checkboxes instead of appending.
(3) your if ( in_array($what[$tax_name], $what) ) will aways be true, as you are checking if an array value is in its own array, so all your values will be in $checkboxes. I think you want to check if the value equals tax_cb,tax_radio, or tax_dd.
try something like this-
if (isset($_GET['submit'])) {
$which_tax_array = array('location', 'genre', 'studio');
$what = array();
foreach ($which_tax_array as $key => $tax_name) {
$what[$tax_name] = $_GET[$tax_name.'do'];
}
foreach ($what as $tax_term => $display_option) {
if ($what[$tax_name] == 'tax_cb') {
$checkboxes .= ','.$tax_term;
} elseif ($what[$tax_name] == 'tax_radio') ) {
$radios .= ','.$tax_term;;
} elseif ($what[$tax_name] == 'tax_dd') ) {
$dropdowns .= ','.$tax_term;
}
}
echo 'cb '.$checkboxes.'<br>';
echo 'radio '.$radios . '<br>';
echo 'dd '.$dropdowns.'<br>';
}