Reputation: 83
This fiddle shows that the dropdown starts at ‘One’. What I want to happen is that the dropdown to start at my default (One) and then once I select a different option (Two), when I refresh the page, the dropdown starts at ‘Two’ instead of ‘One’.
https://jsfiddle.net/USERALPHA32/7r59xkrf/
It should just be as simple as taking the newly selected value and making that the new default select option. I’ve tried a few ways but I cannot get it working. (below code not apart of the fiddle but just showing the concepts I tried in my actual code)
var nSel = $(‘option:selected’, this).detach();
$(this).prepend(nSel);
console.log(nSel.val());
//The above ’nSel’ is the correct value I’m clicking on.
//None of these below worked.
// $('#dropdown option:selected').val(nSel.val());
// console.log($('#dropdown option:selected').val(nSel.val()));
// $("#dropdown").val(nSel.val());
// $("#dropdown").val();
// console.log($("#dropdown").val(nSel.val()));
// $("#dropdown").find(':selected').val();
// $('select').find('option', nSel.val());
// $('#dropdown option:selected', nSel.val());
// $('#dropdown option:selected').val(nSel);
Upvotes: 0
Views: 1000
Reputation: 1
If you want to save a value after refreshing the web you must use cookies or localStorage and then set this variable with the new value.
Instead the traditional refresh you want to "reflesh" with ajax, you can use a global variable in your js file.
COOKIE
Set a cookie
$.cookie("example", "foo"); // Sample 1
$.cookie("example", "foo", { expires: 7 }); // Sample 2
$.cookie("example", "foo", { path: '/admin', expires: 7 }); // Sample 3
Get a cookie
console.log( $.cookie("example") );
Delete the cookie
$.removeCookie("example");
LOCALSTORAGE
var data = localStorage.getItem("key");
if(data){
// Code
}
Upvotes: 0
Reputation: 5529
If you want that your data will be saved even after refresh, you have to use localStorage.
Save your choose in localStorage and fetch him on page load.
When user choose an option you save it with this code:
localStorage.setItem("key", "yourOption");
And on document load you check if key exists:
var data = localStorage.getItem("key");
if(data){
// here you change dropdown value.
}
You can choose if you want to delete value in localStorage so in next page refresh it will be clean.
Upvotes: 3