Reputation: 1
I am new to programming, what I am trying is when a user selected option from a select, the next time user visit the page or refresh the page the user will see his last selected option as selected already.
<!DOCTYPE html>
<html>
<body>
<select id="Example">
<?php
$value = "<script>document.write(value)</script>";
$val = "1";
$val2 = "2";
?>
<option value="1" <?php if ($val == $value){ ?>selected <?php } ?> >One</option>
<option value="2" <?php if ($val2 == $value){ ?>selected <?php } ?> >Two</option>
<option value="3">Three</option>
</select>
<script>
var sel = document.getElementById('Example');
var value = sel.options[sel.selectedIndex].value;
</script>
</body>
</html>
I am using the above code but I am not getting the desired output, please help me I am really stuck. If this is possible in JavaScript I will also be appreciated. Thanks in Advance.
Upvotes: 0
Views: 79
Reputation: 494
<form action="" method="post">
<label>Country</label>
<select id="country" name="country" onchange="myFunction(this.value)">
<option value="india">India</option>
<option value="australia">Australia</option>
<option value="canada">Canada</option>
<option value="usa">USA</option>
</select>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
var val = localStorage.getItem("CountryValue");
document.getElementById('country').value = val;
// This function will store data in localstorage on client browser.
function myFunction(value) {
localStorage.setItem("CountryValue",value);
}
</script>
Upvotes: 0
Reputation: 177684
Database, Cookies or localStorage
window.onload=function() {
var val = localStorage.getItem("example");
if (val) { document.getElementById('Example').value = val }
document.getElementById('Example').onchange=function() {
localStorage.setItem("example",this.value);
}
}
Upvotes: 1