user1478822
user1478822

Reputation: 35

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?

Upvotes: 1

Views: 232

Answers (2)

David Cheung
David Cheung

Reputation: 858

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.

Upvotes: 3

John Conde
John Conde

Reputation: 219924

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>

Upvotes: 0

Related Questions