Presetting a select element - php

I have a form with several input fields plus a select element that has several dropdown options. The user fills in the input fields and selects one of the drop down options and submits the form. The php handler for the form saves the form inputs in a database and builds a page from these inputs. An edit link on the built page returns to the form page with the fields preset to what they were the last time the form was submitted, so the editing can start from the last state submitted.
Presetting the input fields is easy, where I can just specify value=<?php echo [saved value from last submission];?> But presetting the select element to the last value chosen is not so easy. I know that jQuery has $('select#id').val("4"); which will preset the select#id element to option #4, but how can I trigger this when the form page is loaded again? Presettng the inputs by setting value= doesn't seem to generate anything that can be sensed by jQuery.
Thanks for any ideas.

Set the attribute selected for one of the options you want to be the selected. So, something like <option <?php echo 'selected="selected"';?>>4</option>.
Edit:
Either you can generate the options in a loop having the values in an array, checking each iteration if the current option was the one that was selected by the user and set the selected attribute of that one option, or you can just use the following, although not so elegant, approach:
<select name="number">
<option value="1" <?php echo ($_POST['number'] == '1') ? 'selected="selected"' : ''; ?>>1</option>
<option value="2" <?php echo ($_POST['number'] == '2') ? 'selected="selected"' : ''; ?>>2</option>
<option value="3" <?php echo ($_POST['number'] == '3') ? 'selected="selected"' : ''; ?>>3</option>
<option value="4" <?php echo ($_POST['number'] == '4') ? 'selected="selected"' : ''; ?>>4</option>
</select>

user2570380:
I think your edited solution would work so I gave you credit. But I've found another way that works that may be even more elegant. In the HTML of my PHP file I've placed at the bottom:
<script>
jQuery('select#age_group').val(<?php echo $age_group?>);
</script>
</body>
Here select#age_group is the select element I want to preset and $age_group is the value coming into PHP that I want to set into the select element.

Related

Displaying Select on GET

If I have a select form, for example:
<form action='?' method='get' name='form_filter' class="sortoptions" >
<select name="sort" >
<option value="None">None</option>
<option value="PriceLow">Price (Low to High)</option>
<option value="PriceHigh">Price (High to Low)</option>
<option value="NameAZ">Name (A-Z)</option>
<option value="NameZA">Name (Z-A)</option>
</select>
I'm submitting using the GET method but need a way of when its been submitted and on the results page the option which was selected to be displayed.
So say if 'Price (High to Low)' is selected it will then be displayed in the select box on the results page after its been submitted
Any ideas?
Thanks!
When you will submit the form (assuming there is a submit button in your form), all data will be sent to PHP and you will retrieve all your data inside $_GET (the global var)
$_GET['sort']
will contain the value selected.
Then if you want to pre select, you just have to add some PHP code inside your HTML
<option value="PriceLow" <?php echo ((!empty($_GET['sort']) && $_GET['sort'] == 'PriceLow') ? 'selected="selected"' : '') ?>>Price (Low to High)</option>
You have to do the same for each option of the select.
That will allow you to preselect the good option after a first submit.
Solution 2:
If you don't wan to insert too much PHP inside your HTML code, you can store the posted value inside a javascript var and then, select the good option when the DOM is loaded (using a good JS library like jQuery for example)
Your HTML code:
<select name="sort" >
<option value="None">None</option>
<option value="PriceLow">Price (Low to High)</option>
<option value="PriceHigh">Price (High to Low)</option>
<option value="NameAZ">Name (A-Z)</option>
<option value="NameZA">Name (Z-A)</option>
</select>
And some JS code in <script> tag
// Need jQuery !
$(document).ready(function() {
// Generate the selected var in JS using the value in PHP
var selectedOption = '<?php echo $_GET['sort']; ?>';
// Select the selected option and append the selected attribute
$("select[name=sort] option[value=" + selectedOption + "]").attr('selected', 'selected');
});
This code will automatically select the good option once the page is loaded.
Info: The good point is that you have a more clear and maintanable HTML code. The bad point is that if JavaScript is not enabled on the client, your automatic selection will not work (it will always work when you are using PHP to add "selected" in HTML). So you have to evaluate pro and cons and make your choice.
Note: you can leave the action empty instead of "?"
$_GET['sort']
in the submitted page will give you the selected option. And to check whether the form has been submitted:
if(isset($_GET['submit'])) {
// do something with the result
}
where 'submit' is the name of your submit button.
Try this code, it's probably what you would want. I assume you're writing it in your .php files or your other extensions, perhaps .html have php code enabled in them (maybe via .htaccess file)
<?php if (isset($_GET['sort'])){ ?>
<?php $sel= $_GET['sort']; # format? ?>
<strong><?php print($sel);?></strong>
<?php } ?>
<form action='' method='GET' name='form_filter' class="sortoptions" >
<select name="sort" >
<?php
$ff = Array(
'None' => 'None',
'PriceLow' => 'Price (Low to High)',
'PriceHigh' => 'Price (High to Low)',
'NameAZ' => 'Name (A-Z)',
'NameZA' => 'Name (Z-A)',
);
?>
<?php foreach ($ff as $v => $t) {?>
<option value="<?php print($v);?>" <?php if (isset($_GET['sort']) && ($_GET['sort'] == $v)) print('selected="selected"');?>"><?php print($t);?></option>
<?php } ?>
</select>
<input name="submit" type="submit" />
</form>

pre-selected values for a dynamic drop-down box

Here is my problem, I have dropdown which used to save the selected option to a SQL database. Now I have an Edit option where the same dropdown is created dynamically to give the user to select and alternate option and save the edit. When the edit page launches I want the dropdown to be pre-selected the value already saved in the database.
I use following code to get done the similar thing with a textbox but strugling to put the same value attribute to the dropdown.
<input name='routename' type='text' value='".htmlentities($row['route'])."'> // This is working for the textbox
can someone tell me how to do this with a dropdown box? Thanks
It's a little more complicated but can be achieved with this:
<select name="something">
<option value="1"<?=($row['something'] == 1)? ' selected="selected"':''?>>Option 1</option>
<option value="2"<?=($row['something'] == 2)? ' selected="selected"':''?>>Option 2</option>
</select>
You will have to use conditional code as you generate your <option> nodes like this:
<?php
echo '<option ';
if ($value == $selected_value)
echo 'selected="selected"';
echo 'value="'.htmlspecialchars($value).'" />';
?>
while($row=mysql_fetch_row($rs)){
if($row['id']==$value){
$selected='selected';
}else{
$selected='';
}
echo '<option value="$row['id']" $selected >$row['value']</option>';
}

jQuery UI chained select-menu. Form resets when button is clicked

I am using a chained select-menu to guide the visitor trough some questions. This works like a charm, however, in the end the user has to click a button to send all values to a PHP-script. This also works without a problem, however, when the page reloads (because the button sends the form to the same page), all fields are hidden again and this is not what i want.
I would like the chained selection menu's to be shown when items in them are "selected" when the page reloads. Using PHP i simply test if a field was selected and add that status to the select-menu. But they remain hidden until you manually select everything again.
I think it's just a minor adjustment in the JS-part. But my limited knowledge of JS leaves me without a solution.
Sources
jsFiddle
Chainedselection script
jQuery UI and selectmenu
Since the form submits to itself the values the user chose will be available in either $_GET or $_POST (depending on whether the action of your form is get or post).
The best approach would then be to use those values to set the selected attribute on the appropriate <option> node using something like this.
$selectedC1Value = '';
<? if isset($_POST['c1']) { ?>
$selectedC1Value = $_POST['c1'];
<? } ?>
<select name="c1" id="c1" >
<option value="" <? if ($selectedC1Value == '') { echo 'selected'; } ?>>
--
</option>
<option value="age" <? if ($selectedC1Value == '') { echo 'selected'; } ?>>
Age
</option>
<option value="education" <? if ($selectedC1Value == '') { echo 'selected'; } ?>>
Education
</option>
<!-- etc -->
</select>
This would have to be repeated for each <select> in your <form>.

How can I retain a option from a select field?

I have a <select>:
<select id="countries">
<option value="1">USA</option>
<option value="2">Spain</option>
</select>
The user selects an option, then he press a send button to make a query, thru PHP. The result of the query appears in the same page, so the page reloads.
How do i retain the selected option? when the page reloads??
I mean, if they select spain, how can I see spain again when the page reloads?
You need to first give your select dropdown a name.
For example:
<select id="countries" name="countries">
Then you will have access to the value in your PHP when the form is submitted. The value can be retrieved like this in PHP (after submit):
$countries = $_POST['countries'];
Then you can do something like #JohnConde did by setting the selected attribute with PHP.
Here's a very basic way to do it:
<option value="1"<?php if (1 === (int) $_POST['countries']) echo ' selected="selected"'; ?>>USA</option>
<option value="2"<?php if (2 === (int) $_POST['countries']) echo ' selected="selected"'; ?>>Spain</option>

php form validation using session variable

I have a sign-up form in php, which sends data to another php form for insertion into mysql
If any of the fields are missing, an error mesage is sent back to sign-up form using session variable (value="<?php echo $_SESSION['error']; ?>") along with all the fields the user had already filled up ( so that they dont have to fill it up again ) using session variables as well..
for text boxes im using value="<?php echo $_SESSION['fname']; ?>" which works fine.. but this doesnt seem to work for drop down boxes or radio buttons..
any suggestions?
Drop down boxes and radio buttons use a selected or click index. You need to check for each one if it was selected or clicked and give it the appropriate attribute.
<?php if($_SESSION['dropBox1'] == "value") echo ' selected="selected"'; ?>
First, you shouldn't submit the form to another page for validation. Do it in the current page. And drop down lists and radio buttons value attribute is the value that is tied to the selection. Not what is displayed or in any way tells it that it is the selected item. #James beat me for code on how to show which is selected.
<select>
<option value="0" <?php echo $_SESSION['dropBox1'] == "0" ? ' selected="selected"' : '' ?>>option1</option>
<option value="1" <?php echo $_SESSION['dropBox1'] == "1" ? ' selected="selected"' : '' ?>>option2</option>
<option>etc..</option>
</select>

Categories