I have a jquery function designed to make form values persistent by setting a cookie for each value and populating the field from it on page load.
It looks like this:
$(function () {
var bindToCookie = function (identifier, alias) {
var timetoKeep = 7;
var readVal = CookieManager.readCookie(alias);
//console.log(identifier + 'value = ' + readVal);
if (readVal) {
//console.log(identifier + 'value set= ' + readVal);
$(identifier).val(readVal);
}
$(identifier).on('change', function () {
CookieManager.createCookie(alias, $(identifier).val(), timetoKeep);
});
};
bindToCookie('#todatepicker', 'todate');
bindToCookie('#fromdatepicker', 'fromdate');
bindToCookie('#languagepicker', 'language');
bindToCookie('#stationpicker', 'station');
bindToCookie('#programpicker', 'program');
bindToCookie('#sourcepicker', 'sourcepicker');
});
This is working fine for all of my single values, but the field '#sourcepicker' is a multiple select, and it only works as expected when a single value is selected. For example if I select value 1, it loads with 1 selected, but if I select 1 and 4, the cookie is saved with a value of 1,4 and nothing is selected on reload. I seem to be able to set multiple value for it in jquery using the syntax $('#sourcepicker').val(["1","4"]); Whereas if I do $('#sourcepicker').val([1,4]);
How do I reformat this function to correctly store and retrieve values for the multiple select in a cookie?
A multi-select returns a string (comma-separated list) of the selected values - you need to write an optional bit of code that deals with the comma-separated list when it finds it in the cookie:
if (readVal.indexOf(",") > -1) {
/* make an an array out of readVal,
select the options in the multi-select
and so on */
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.