Steve
Steve

Reputation: 4908

Presetting a select element

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.

Upvotes: 0

Views: 64

Answers (2)

Steve
Steve

Reputation: 4908

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.

Upvotes: 0

user2570380
user2570380

Reputation:

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>

Upvotes: 1

Related Questions