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.
Related
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
}
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">
I am using HTML inside PHP like this.
for($i=0;$i<count($arrSql);$i++)
$opt.="<option". if($_GET['pId'] == $arrSql[$i][0]){ echo "Selected";} ."value=".$arrSql[$i][0].">".$arrSql[$i][1]."</option>";
I have tested it for a long time and it looks correct, but it is showing an error and I don't know where the bug is.
You can't use concatenation and if together. Change it to:
for ($i=0;$i<count($arrSql);$i++) {
$opt .= "<option"
. ($_GET['pId'] == $arrSql[$i][0] ? " selected" : '')
."value=".$arrSql[$i][0].">".$arrSql[$i][1]."</option>";
You forgot the spaces.
Try following:
for($i=0;$i<count($arrSql);$i++)
$opt.="<option". ($_GET['pId'] == $arrSql[$i][0] ? ' selected="selected" ' : ' ') ."value=".$arrSql[$i][0].">".$arrSql[$i][1]."</option>";
Your echo call is not needed in this place. Your statement only concatenates strings and does not print them.
Additionaly it's not possible to use an if statement inside a string concatenation. However the if shortcut, the so called ternary operator is applicable in this situation.
And as pointed out in an other answer there is also a space missing before the selected part.
for($i=0;$i<count($arrSql);$i++) {
$opt .= "<option "
.($_GET['pId'] == $arrSql[$i][0]) ? "Selected" : ""
."value=" .$arrSql[$i][0]
. ">" .$arrSql[$i][1]. "</option>";
}
An alternative using if that might be more clear is:
for($i=0;$i<count($arrSql);$i++){
$opt .="<option ";
if ($_GET['pId'] == $arrSql[$i][0]){
$opt .= "Selected";
}
$opt .= "value=" .$arrSql[$i][0]. ">" .$arrSql[$i][1]. "</option>";
}
If you want to, you can even inline the array accesses into the string by using curly braces leading to this last line: (more here)
$opt .= "value=${$arrSql[$i][0]}>${$arrSql[$i][1]}</option>";
For the future you might want to enable error output in your scripts. This would have indicated the main error.
If I have a line like this,
<option value="someval">somval</option>
how can I position the cursor after the last quotation of value and put something like abcdef?
So the output would be
<option value="somval" abcdef>somval</option>
with PHP?
I want to do this dynamically and I can't figure out how to do it. I'm looking at strpos(), but I don't see how it can be done. I'll be posting a bunch of option tags into a textbox and code will be generated. so I'll have a lot of option fields.
#martin - Say I have a huge dropdown and each option lists a country that exists. Rather than having to manually type out something like this:
$query = $db->query("my query....");
while($row = $db->fetch($query)) {
<select name="thename">
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
<option value="someval" <?php if($row['someval'] == 'someval') { print "selected"; } ?> >someval</option>
... Followed by 100 more, because there are a lot of locations to list.
</select>
How can I post all the options I have into a textbox and have the above code automatically generated to save a lot of time?
Using your example you would do:
while($row = $db->fetch($query)) {
printf('<option value="someval"%s>someval</option>',
($row['someval'] == 'someval') ? ' selected="selected" ' : '');
}
This would go through the rows and output an option, replacing the %s with the attribute selected="selected" if $row['someval'] is equal to someval. However, the above is rather pointless, because all option elements will have the same value and text, so try
while($row = $db->fetch($query)) {
printf('<option value="%s"%s>%s</option>',
$row['country-code'],
($row['country-code'] === $selection) ? ' selected="selected" ' : '',
row['country-name']);
}
With $selection being anything you want to compare against. Replace the keys in $row with appropriate keys from in your database.
Note: The usual disclaimers about securing your output apply
You could capture (value=".+?") and replace it with $0 abcdef.
<?php
$string = '<option value="someval">someval</option>';
print preg_replace("/(value=\".+?\")/i", "$0 abcdef", $string);
?>
Which outputs the following:
<option value="someval" abcdef>someval</option>
With PHP, you can generate a whole string with any text you wish. Where do you have your original string? In a variable or a text file?
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');