Avionicom
Avionicom

Reputation: 191

Remember the selected value once refreshed the page

In a page containing a form with select fields, I need to remember the previuos choice (if any) of, for example, the selected state. I want to do it via PHP embedded in JS, where I'm wrong?

<script>
<?php
if(isset( $_GET["state"] )){
$selected_state =  $_GET["state"];
?>
$("#state option[<?php echo $selected_state ?>]").attr("selected", "selected");
<?php } ?>
</script>

Thank you in advance!

Upvotes: 0

Views: 913

Answers (2)

Jonast92
Jonast92

Reputation: 4967

You can use sessions in PHP to remember certain data.

For example:

session_start();

$foo = 'John';
$_SESSION['user'] = $foo;
// Refresh the browser.
echo $_SESSION['user'];
// Outout: 'John'.

Check out http://php.net/manual/en/ref.session.php if you want to learn more.

Be careful of what you store in sessions though, don't store critical data in them.

Upvotes: 1

Shedokan
Shedokan

Reputation: 1202

Replace:

$("#state option[<?php echo $selected_state ?>]").attr("selected", "selected");

With:

$("#state option[value='<?php echo $selected_state ?>']").attr("selected", "selected");

The problem is with the jQuery selector #state option[SOMETHING] which checks if the element option has an attribute called SOMETHING, where you want to see if the value of an option is equal to SOMETHING so we use #state option[value='SOMETHING'].

You can find the jQuery selectors docs here: http://api.jquery.com/category/selectors/

Upvotes: 1

Related Questions