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">
Related
I have this easy select in PHP as echo (using Chosen JS):
echo" <tr>
<th>By country:<br />
<select id=\"firstselect\" name=\"country[]\"
data-placeholder=\"Country...\" multiple class=\"chosen-select\">
<option value=\"dontcare\">dontcare</option>";
foreach ($states as $state) {
echo "<option value=\"" . $state->stat .
"\" >" . $state->stat . "</option>";
}
echo "</select> </th></tr>";
after submitting from and refreshing page values are not as selected.
If i have select with only one choice this is working for me:
var my_val = '<?=$_POST['price']?>';
$("#cenan").val(my_val).trigger("chosen:updated");
but i dont know how to set it as selected in case of array. Can you help me and show me some code? I spent hours and hours without any result.
You are POSTing the form data to the same page and then refreshing it, right?
If so then you can just change your PHP slightly to mark the chosen options as selected when the page refreshes by checking if its value exists in the $_POST['country'] array.
Also, as you are enclosing your echo output in double quotes there is no need to escape variables as PHP will parse them anyway, just use single quotes within the string where you want quotes in your HTML. Much easier on the eye.
foreach ($states as $state) {
if ((!empty($_POST['country'])) && (in_array($state->stat, $_POST['country']))) {
echo "<option value='$state->stat' selected>$state->stat</option>";
} else {
echo "<option value='$state->stat'>$state->stat</option>";
}
}
Lets suppose you have HTML select like following :
<select id='firstselect' multiple class="chosen-select" >
<option value='a'>A</option>
<option value='b'>B</option>
<option value='c'>C</option>
</select>
Here is the solution :
<?php
$arr = ['a','b']; // PHP Sample Array
?>
var js_json = '<?php echo json_encode($arr); ?>';
var js_json_string = JSON.stringify(js_json);
var js_json_array = JSON.parse(js_json_string); // ['a','b']
// initialize
$("#firstselect").chosen();
// Loop for making HTML <select> options selected.
$.each(js_json_array,function(i,v){
$('#firstselect option[value=' + v + ']').attr('selected', true);
});
//Updating Chosen Dynamically
$("#firstselect").trigger("chosen:updated");
What would be the best way to set tag selected value?
<select id="attr_field_10" name="config_eph_payment_type">
<option value="5">First</option>
<option value="1">Second</option>
<option value="2">Third</option>
<option value="3">Fourth</option>
<option value="4">Fifth</option>
<option value="7">Sixth</option>
</select>
The value comes from $config_eph_payment_type variable (5, 1, 2, 3, 4 or 7).
Something like this should work:
$options = array(
5 => "First",
1 => "Second",
...
7 => "Sixth"
);
echo "<select id=\"attr_field_10\" name=\"config_eph_payment_type\">";
foreach ($options as $k => $v) {
echo "<option value=\"$k\"";
if ($k == $config_eph_payment_type)
echo " selected";
echo ">$v</option>";
}
echo "</select>";
What we basically do is to store the options into an associative array. Then, we loop through it and keep checking if the value is equal to the variable $config_eph_payment_type.
<option value="5"<?php if ($config_eph_payment_type == 5) print ' selected="selected"'; ?>>First</option>
This is the easiest way to do it. You could also put the if at the beginning of the file and then define a variable, this would make the HTML code more readable
<?php
//at beginning
if ($config_eph_payment_type==5)
$fiveSelected = ' selected="selected"';
else
$fiveSelected = '';
?>
in your code
First
I have a standard select box in my php form for my website containing a list of counties in the UK, an example of which is shown below:
<p class='form_title'>County<br>
<select id="county" name="county">
<optgroup label="England">
<option>Bedfordshire</option>
<option>Berkshire</option>
<option>Bristol</option>
....
<option>Wiltshire</option>
<option>Worcestershire</option>
</optgroup>
<optgroup label="Wales">
<option>Anglesey</option>
...
<option>Radnorshire</option>
</optgroup>
<optgroup label="Scotland">
<option>Aberdeenshire</option>
...
<option>Wigtownshire</option>
</optgroup>
<optgroup label="Northern Ireland">
<option>Antrim</option>
...
<option>Tyrone</option>
</optgroup>
</select>
</p>
Once a user has submitted details, they can then edit them.
I therefore need a way to have selected the option that they previously chose, given that I have the option they chose saved in word form, such as Bedfordshire.
I know I need to add the word selected to one of the options, but I was wondering if there was a better way to do it than a massive case statement.
Thanks
You should set an option value for each option to track the value.
Also you should be generating that from a database and then you can set selected based on a $_GET or $_POST:
for example:
foreach($county as $name){
$selected = '';
if($name == $_GET['name']){
$selected = ' selected="selected"';
}
echo '<option value="'.$name.'"'.$selected.'>'.$name.'</option>';
}
this doesn't include your optgroup but that also should come from database.
Try something like this:
foreach($places as $place) {
$selected = $prevSelectionId == $place['id'] ? " selected='selected' " : "";
echo "<option $selected value='".$place['id']."'>".$place['name']."</option>";
}
</select>
I have an issue getting variables using PHP in a tablet site I have been working on. I have a search form on the homepage that passes variables to a list page. I then have the same search form in a 'refine search' dialog box which should pre-select the appropriate values depending on what has been passed, using PHP.
The problem is I can't seem to get the variables that have been passed (using PHP). For example I have this field in my search:
<select name="propertyType" id="propertyType">
<option value="">Any Type</option>
<option value="1"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="1") { echo ' selected'; } ?>>Houses</option>
<option value="2"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="2") { echo ' selected'; } ?>>Flats/Apartments</option>
<option value="3"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="3") { echo ' selected'; } ?>>Bungalows</option>
<option value="4"<?php if(isset($_GET['propertyType']) && $_GET['propertyType']=="4") { echo ' selected'; } ?>>Other</option>
</select>
But when I pass any of these values my code does not pick them up and echo the relevant 'selected'.
The tablet site can be found here: http://muskermcintyre.co.uk/tablet Any help would be much appreciated!
Thanks.
I suggest you following syntax:
<?php
$values = array(
0 => 'Any Type',
1 => 'Houses',
2 => 'Flats/Apartments',
3 => 'Bungalows',
4 => 'Other'
);
$current = (int) $_GET['propertyType'];
?>
<select name="propertyType" id="propertyType">
<?php
foreach ( $values as $key => $value ) {
$selected = $key == $current ? 'selected="selected"' : '';
echo "<option value='$key' $selected >$value</option>";
}
?>
</select>
I've had a similar problem in the past and got round it by getting the query string using Javascript/jQuery.
A quick search gave me this which might help you if you go down a similar route:
How can I get query string values in JavaScript?
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?