Reputation: 181
I have this https://jsfiddle.net/1zqgeq79/2/
This is the jquery I'm using to make the page refresh when a select has been changed and now I just need it to keep that selected option after the page loads.
$('.ProductDetails select').change(function () {
location.reload();
});
Since I have multiple items I know a (this) will have to be used, but I'm still learning jquery. Thanks for the help!
Upvotes: 5
Views: 35211
Reputation: 171679
When you reload the page... all your script runs the same way as when you loaded it the first time. Nothing is saved or accessible from previous load.
You can however store data in cookies or localStorage and access that when page loads.
Try something like:
$(function(){
// get stored value or make it empty string if not available
var storedValue = localStorage.getItem('prod-detail') || '';
$('.ProductDetails select').change(function () {
// store current value
var currValue = $(this).val();
localStorage.setItem('prod-detail', currValue );
// now reload and all this code runs again
location.reload();
})
// set stored value when page loads
.val(storedValue)
});
A better solution might be to use ajax to update your cart stored on server and set all stored values there when page loads
Upvotes: 2
Reputation: 205
Use sessionStorage instead of localStorage if you don't want to keep the data parmanently after closing the browser.
I replaced the code with:
var selectedProduct = sessionStorage.getItem("product");
if(selectedProduct != undefined || selectedProduct != null){
$(".ProductDetails select").first().find(":selected").removeAttr("selected");
$(".ProductDetails select").find("option").each(function () {
if ($(this).val() == selectedProduct) {
$(this).attr("selected", true);
}
});
}
$('.ProductDetails select').change(function () {
sessionStorage.setItem("product", $(".ProductDetails select").first().val());
location.reload();
});
Just go to: https://jsfiddle.net/1zqgeq79/3/
I did for first dropdown only.
Upvotes: 5
Reputation: 120
You can either add a query string parameter before reloading.
var url = document.location;
document.location = url + "?select=" + $(this).val();
So when the page is loading you can read this parameter and act as you want.
You can also do this using a cookie. jQuery allows you do do that. Check out this link: http://plugins.jquery.com/cookie/
Upvotes: -1