Keep a Select Box Selected after Submit - php

On my website, user's are allowed to filter games by Genre. When a user chooses a genre from the select box and hits submit, the page uses GET to see what the filter was. Now the filter works fine, the problem is that the select box's selection goes to the default one (Which says "All".)
I want it so that after a user submits their filter request, the select box will keep that selection after the page reloads.
There's only one way I could think of to do this but it would require adding in PHP into every option there is. Are there any simpler ways to go about doing this with PHP or jQuery?

You don't want to do this with jQuery. There it is not for.
Just have the options in an array in PHP and loop over it. If the looped value matches the currently selected option, then just add the selected attribute.
E.g.
foreach ($options as $value => $label) {
echo '<option value="' . $value . '" ' . ($selected == $value ? ' selected' : '') . '>' . $label . '</option>';
}

Assuming you're doing a full form submit the selected option is only going to be available to the server-side code, once it gets back to the client to use jQuery you won't have that (unless you try to use cookies before the form submit, but bleh).
I'd use PHP in the option tag and echo selected="selected" if the option matches up with the selected option.
If you want to avoid a lot of duplicated code why not do something like this:
<select name="test">
<?php
$options = array(1 => 'Option 1', 2 => 'Option 2', 3 => 'Option 3');
foreach ($options as $key => $value) {
echo '<option value="' . $key . '"' . ($key == $_GET["test"] ? ' selected="selected"' : '') . '>' . $value . '</option>';
} ?>
</select>

you can do it without a loop just change the 6 to whatever value you want when you render the page
$("#$optionId[value=6]").attr('selected','selected');

Related

How to update radio group status in a metabox?

I have implemented radio-group option in WordPress metabox. I got the desire radio group in meta box with respective label, but I failed to update my checked status on selecting radio or saving the post where I am using it. I think there is something I need to put.
<div class="my radio group">
<h2>my radio group </h2>
<?php
$cars = array('BMW', 'FERRARI', 'PORSCHE', 'BENTALI', 'MRX', 'CHEVROLET');
foreach ($cars as $car) {
echo '<input name="my-best-car" type="radio" onchange="javascript:document.post.submit()"';
$option = 'id=" ' .$car . '"';
$option = '<value="' . $car . '"';
if ($car == $my_favorite_car) $option .= "checked";
$option .= '>';
$option .= '<label for=" '.$car .' ">' . $car .' ';
$option .= '</label>';
echo $option;
}
?>
</div>
WordPress meta box save function is also added. My other option type like text, select & checkbox updating properly.
While I trying to update my RADIO-GROUP meta values using:
update_post_meta($post_id, 'my-best-car', $_POST['my-best-car'], true);
Ok I found your mistake in foreach loop you have one < extra before the value so the line would look like this:
$option = 'value="' . $car . '"';
Also your js is not submitting the form so just add js function in head like this for example:
<script>
function submitOnClick(formName){
document.forms[formName].submit();
}
</script>
And in the form instead of:
onchange="javascript:document.post.submit()"
put
onclick="submitOnClick(\'myForm\')"
I tried it and it works you just need to rename your form name accordingly

How to select a <select> statement from database?

I wasnt quite sure how to word the question correctly - but this is merely just out of interest really. Constantly I am having to load information from a database and pre-populate a form with the values. So in the case of the textbox, its easy, i simply set the value:
<input type="text" value="<?=$foo;?>" name="foobar">
However when I come to select boxes I find my code gets quite sloppy, as I need to place a selected value in the line somewhere. So really I have two options, both of which I dislike:
$one = $two = "";
switch ($myval) {
case "1": $one = " selected";
case "2": $two = " selected";
}
and then in the HTML:
<select name="myval">
<option value="1"<?=$one;?>>One</option>
<option value="1"<?=$two;?>>Two</option>
</select>
Or the other option is to place a shorthand if statement in the middle of the select:
<select name="myval">
<option value="1"<?=($myval=="1") ? " selected" : "";?>>One</option>
<option value="1"<?=($myval=="2") ? " selected" : "";?>>Two</option>
</select>
Which looks slightly cleaner, however it still bugs me.
Anyone got any much more efficent ways of doing this? its even more annyoing when It is just a Yes/No drop downbox and I have to write stupid if statements for each value.
The same question applies to checkboxes as well.
Create an array with the data you want in the output. Loop over it. Generate an option element for each item in it.
As an addition to Quentin (just some code to help you out), I tend to use arrays as well, like this:
<select name="myval">
<?php
$options = array(
"1" => "One",
"2" => "Two"
);
foreach ($options as $value => $text) {
echo '<option value="' . $value . '"' . ($myval == $value ? ' selected' : '') . '>' . $text . '</option>';
}
?>
</select>
Well the easiest way for such repetitive outputs is to write yourself a function, for example:
function selectbox(array $options, $name, $value = null) {
$out = '<select name="' . $name . '">';
foreach($options as $key => $text) {
$out .= '<option value="' . $key. '"' . ($key == $value ? ' selected="selected"' : null) . '>' . $text . '</option>';
}
return $out . '</select>';
}
There are really many ways for a cleaner code. Find one or invent your own :)
For select statements, I like to use utility methods. E.g.:
<?= HTML::createSelect($name, $actualvalue, $optionslist, $passthrough) ?>
Something on that line. Read the optionslist and the actualvalue from the DB. Passthrough is for adding HTML decorators, e.g. id, class, etc.

Using PHP function to create a dynamic dropdown menu using arrays: dropdown doesn't populate

I am trying to dynamically build a drop down menu using PHP. The idea is: the elements are formed from a loop which calls and array. If the array element matches the data held in session then it adds the "selected" attribute to the tag, meaning that the page displays the previously selected option.
I have tried to include one complete set of code here, all the way from defining the variables from session data to echoing the HTML for the form element.
It doesn't currently work - the drop down menu appears, but is blank, and has no options. I've debugged it with ideone and it seemed to run successfully, and I can't see where I am going wrong, however this is my first PHP function! So I'm sure I've screwed it up somehow :)
Any help much appreciated.
<?php
session_start();
//if the session data has been set, then the variable $sv_02 is defined
//as the data held in the session under that name, otherwise it is blank
if (isset($_SESSION['sv_02'])) {$sv_02=$_SESSION['sv_02'];} else {$sv_02="";}
//define the array
$dm_sv_02 = array('-Year','-2012','-2011','-2010','-2009');
//create the function
function dropdown($dropdownoptions, $session_data)
{
foreach($dropdownoptions as $dropdownoption){
if($session_data == $dropdownoption){
echo '<option value="' . $dropdownoption . '" selected>' . $dropdownoption . '</option>';
} else {
echo '<option value="' . $dropdownoption . '">' . $dropdownoption . '</option>';
}
}
}
//echo the HTML needed to create a drop down, and populate it with
//the function which should create the <option> elements
echo '<select name="sv_02">';
dropdown($dm_sv_02, $sv_02);
echo '</select>';
?>
Try this:
foreach ($dropdownoptions as $dropdownoption) {
echo ($dropdownoption == $sv_02) ? "<option selected=\"selected\" value=\"$dropdownoption\">$dropdownoption</option>" : "<option value=\"$dropdownoption\">$dropdownoption</option>";}
This turned out to be a result of the fact I was using {smarty} tags to build my php, the code was as written but only worked when it was all included in one smarty tag, I'm not sure I understand why that should be the case but in any regard it was fixed by including it all in one tag.

PHP Form Error Validation

I'm working on a php form with some validation rules.
If some of the fields are left blank that are require the form will report and error message and ask the user to complete the field.
The form currently keeps the values of the $_POST data so that if errors occur the data which is in the field remains.
I am having a problem with two fields(drop down lists) which are populated with data from a database.
If I complete these fields but there is a error elsewhere the form displays with the values in the drop down list but when I correct the errors and try submit the form it tells me that the drop down list fields are empty.
Here is the code for them
<! Drop Down Menu to get student names from database !>
<SELECT NAME=studentName >
<OPTION VALUE=0 selected="selected" >
<?php if(isset($_POST['studentName'])) echo $_POST['studentName'];?>
<?php echo $options1?>
</SELECT>
Any idea's why this is happening?
For starters, <option value=0 selected="selected"> means that option 0 will always be selected.
You could do something like the following, excuse me if this snippet has bugs, but it should give you a general idea of how you could achieve what you want to:
<?php
$myOptions = array(
'0' => ' --- nothing selected ---',
'1' => 'Apples',
'2' => 'Bananas',
// ...
);
?>
<select name="studentName">
<? php
foreach($myOptions as $key => $value ) {
$selected = isset($_POST['theOption']) && $_POST['theOption'] == $key ? 'selected="selected"' : "";
echo '<option value="' . $key . '" '. $selected . '>' . $value . "</option>";
}
?>
</select>
You can cleanup the above a bit using the alternative PHP syntax:
http://php.net/manual/en/control-structures.alternative-syntax.php
This isn't part of your bug, but just a good practice consideration, some of your HTML tags and their attributes are uppercase, and it's common nowadays to use lowercase. It's more standard this way.
You shouldn't echo $_POST['studentName']; you should check it against the value of each of your options (which should be an array in PHP, which you convert to a list of <option>s in a foreach loop), and set the selected attribute if it matches.
On a sidenote, your HTML is invalid; some attributes are not quoted, and a comment should be in <!-- ... -->, not <! ... !>.

Setting value of dropdown box to last submitted value with javascript

I have the following dropdown box
<form name="myform" method="POST" ACTION="songs.php">
Select Category: <select id="sel" name="categories" onchange="document.myform.submit()">
And all the options follow after. When the user makes a selection, the category is brought up below using PHP and MYSQl based on the selection containing a list of songs etc.
However, the dropdown box always defaults back to the first value in the list of options. How do I make so that the dropdown box will set the selected option to the last submitted value? Thanks in advance!
You can't do that with JS as it has no direct access to POST request parameters. Rather let the server side language (which is in your case PHP) print the selected attribute on the <option> element whenever the submitted value matches the option value.
E.g.
foreach ($options as $value => $label) {
echo '<option value="' . $value . '"' . ($selected == $value ? ' selected' : '') . '>' . $label . '</option>';
}

Categories