jquery - How to retain the dropdown values after selection -
the below code set select 2 dropdown values on page, works fine, however, since page refreshed when 1st dropdown selected, dropdpwn values not retained.
how retain dropdown values ?
$(document).ready(function() { $('.boxy').hide(); var drop1value = ''; var drop2value = ''; var cntys = geturlvars()['cntry']; var pis = geturlvars()['pi']; $("#drop1").on("change", function() { var drop1value = $('#drop1').val(); if (drop1value == "") { $('#content').hide(); } else { drop1value = $('#drop1').val(); } var burl = document.location.origin + document.location.pathname + '?cntry=' + drop1value + '&pi=' + pis; window.location.href = burl; }); $("#drop2").on("change", function() { var drop2value = $('#drop2').val(); if (drop2value == "") { $('#content').hide(); } else { drop2value = $('#drop2').val(); } var burl = document.location.origin + document.location.pathname + '?cntry=' + cntys + '&pi=' + drop2value; window.location.href = burl; }); }); function geturlvars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexof('?') + 1).split('&'); (var = 0; < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }
jquery supports method chaining. can utilize set value this:
$('myselector').on('...', function () {}).val(myvalue)
in case, correct code:
$(document).ready(function() { $('.boxy').hide(); var drop1value = ''; var drop2value = ''; var cntys = geturlvars()['cntry']; var pis = geturlvars()['pi']; $("#drop1").on("change", function() { var drop1value = $('#drop1').val(); if (drop1value == "") { $('#content').hide(); } else { drop1value = $('#drop1').val(); } var burl = document.location.origin + document.location.pathname + '?cntry=' + drop1value + '&pi=' + pis; window.location.href = burl; }).children('[value="'+cntys+'"]').prop('selected', true); $("#drop2").on("change", function() { var drop2value = $('#drop2').val(); if (drop2value == "") { $('#content').hide(); } else { drop2value = $('#drop2').val(); } var burl = document.location.origin + document.location.pathname + '?cntry=' + cntys + '&pi=' + drop2value; window.location.href = burl; }).children('[value="'+pis+'"]').prop('selected', true); }); function geturlvars() { var vars = [], hash; var hashes = window.location.href.slice(window.location.href.indexof('?') + 1).split('&'); (var = 0; < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }
Comments
Post a Comment