make a foreach select menu form sticky - php

I want it so that when people make a selection in my form, the selection they made stays after the form is submitted, or if there was an error in the form, the submitted fields still display their choices. I have tried a lot of things and can't get it to work. I looked for about 30 minutes on Stackoverflow and can't find an answer to this.
<form action="article_rating.php" method="post" class="formbox2"><table class="borderie" width="100%" align="center">
<?php
$ratingarray = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 'Make a Selection');
?>
<p><tr><td align="left"><label for="readable" class="label">Readability Factor- Indicate if you feel this is article is easily readable</label></td><td align="right"><select name="readable">
<?php
foreach($ratingarray as $value){
echo '<option value="'.$value .'"';
echo ' selected="selected"';
echo '>' . $value . '</option>';
}
?>
</select>
</td></tr></p>
<p><tr><td align="left"><label for="originality" class="label">Originality Factor- Indicate how original you feel this article is.</label></td><td align="right"><select name="originality">
<?php
foreach($ratingarray as $value){
echo '<option value="'.$value .'"';
echo ' selected="selected"';
echo '>' . $value . '</option>';
}
?>
</select></td></tr></table></form>

Don't echo selected="selected" for every option. Use an if condition to see if a value for each field was provided previously, and only echo selected if the value in the current iteration of the loop matches.
Example (assumes you're posting to the same page):
// In your loop
if (isset($_POST['readable'] && $_POST['readable'] == $value) {
// echo selected
}

Related

How to get the complete value of an option tag?

I have this code using php
<select id="sem" name="y[]">
<option>Year</option>
<?php
$petsa = new DateTime();
$yr=$petsa->format('Y');
$a=$yr+1;//2015
$b=$yr-1;//2013
for($y=$b;$y<=$a;$y++)
{
$bb = $y+1;
echo '<option value="'.$y.'"'.'-'.$bb;
if(isset($_POST['y'])){
if (in_array($y."-".$bb,$_POST['y'])){
echo 'selected="selected"';
}
echo '/>'.$y."-".$bb;
}else
echo "<option value ='$y'"."-"."$bb".">".$y."-".$bb;
echo "</option>";
}
?>
</select>
if(isset($_POST['submit'])){
$sem= $_POST['sem'];//this is from other field
foreach ($_POST['y'] as $yer);
$osql2 = "INSERT INTO sy VALUES('$sem','$ss')";
if (mysql_query($osql2)){
echo "Successfully Added!";
}
This code work well almost but the problem is when i call the value of the option tag it just give me this value $ss=2014 and it should be like this $ss=2014-2015
what is wrong with my code? that code generate SY from 2013-2014 to 2015-2016
please help me.
Look at the generated HTML. Look at where the quotes around the attribute value are. They are currently very wrong.
Stop trying to generate HTML by mashing together lots of different strings. It becomes very hard to see what is going on.
$value = $y . "-" . $bb;
?>
<option value="<?php echo htmlspecialchars($value); ?>">
<?php echo htmlspecialchars($value); ?>
</option>
<?php
I suspect it's your use of quotes here:
echo "<option value ='$y'"."-"."$bb".">".$y."-".$bb;
I would change it to this:
echo "<option value ='$y"."-"."$bb"."'>".$y."-".$bb;
I have moved the second ' to just before the > of the opening option tag.
The single quote ' was for the option tag, and the double quote " was for the PHP string, you were simply cutting the value for option short

Selected in select form field won't highlight selected option

I have the following PHP function:
function pick ($fieldname, $optionvalues, $defvalue=0, $size=0)
{
$checked = $defvalue;
echo "<select name=\"$fieldname\" size=\"$size\">\n";
foreach ($optionvalues as $value)
echo " <option value = \"$value\" ".
(($value == $checked) ? ' selected ' : '') . "> $value </option>\n";
echo "</select>";
}
When I call it with this:
$vals = array('a','b','c','d','e');
pick ('pick2', $vals, 'c');
it won't highlight c, even though in the page source, it is marked as selected.
My page source is:
<select name="pick2" size="0">
<option value = "a" > a </option>
<option value = "b" > b </option>
<option value = "c" selected > c </option>
<option value = "d" > d </option>
<option value = "e" > e </option>
</select>
If I change call function to:
pick('p',$vals,'c')
It works as it is suppose to.
Can someone explain what is wrong with my function?
change this line
(($value == $checked) ? ' selected ' : '') . "> $value </option>\n";
to
(($value == $checked) ? ' selected="selected" ' : '') . "> $value </option>\n";
The HTML IS valid under HTML 5 standards. It's the way that you are refreshing. If you Click the refresh button or hit F5 the browser will remember your selection. You must "go to" the URL again (ie click the address bar and hit enter)
<?php
function pick ($fieldname, $optionvalues, $defvalue='', $size=0){
$checked = $defvalue;
echo '<select name="'.$fieldname.'">';
foreach($optionvalues as $value){
echo '<option value="'.$value.'"'.($checked==$value?' selected':'').'>'.$value.'</option>';
}
echo '</select>';
}
$vals = array('a','b','c','d','e');
pick ('pick2', $vals, 'c');
Why is the browser remembering your selection?
This is an option that is built into most browsers (Save form history usually in Options). Disabling this should ensure that you always reset the form data to it's "original state". The problem with this is that it leaves the form data in the hands of the end user, which is no good.
It is possible to ensure that it always uses the selected not the last remembered by using the autocomplete attribute:
<select autocomplete="off">

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.

Keep a Select Box Selected after Submit

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');

Categories