Reputation: 2053
I've got two conditionals that have very similar code which essentially takes the values from a cookie looks for checkboxes with a specific name and adds a value based on the cookie values.
My question is this seems like very redundant code having this in two conditionals when they essentially do the same thing just switching up the name of the cookie. How would I condense this to make it more compact and not so redundant. I'm banging my head trying to figure this out. Thanks for the help. I learn better by seeing code so samples are very helpful and much appreciated.
$.fn.userLocator = function(opts) {
if($.cookie('userLocation')){
var userLoc = [];
userLoc = $.cookie('userLocation').split(",");
for(i=0; i!=userLoc.length;i++) {
var checkbox = $("input[name='filter-location'][value='"+userLoc[i]+"']");
checkbox.attr("checked","checked");
}
}
if($.cookie('userServices')){
var serviceLoc = [];
serviceLoc = $.cookie('userServices').split(",");
for(i=0; i!=serviceLoc.length;i++) {
var checkbox = $("input[name='filter-service'][value='"+serviceLoc[i]+"']");
checkbox.attr("checked","checked");
}
}
}
Upvotes: 0
Views: 58
Reputation: 178
Why not move this into a function
something like
function checkboxHelper(service)
{
var servicevar = [];
servicevar = $.cookie(service).split(",");
for(i=0; i!=servicevar.length;i++) {
var checkbox = $("input[name='filter-service'][value='"+servicevar[i]+"']");
checkbox.attr("checked","checked");
}
}
you might want to call the method then
checkboxHelper('userLocation');
Upvotes: 0
Reputation: 661
If I were you, I'd try something like:
var cookieNames = {'location' : 'userLocation','service' : 'userServices'};
for(var key in cookieNames) {
var cookieName = cookieNames[key];
if ($.cookies(cookieName)) {
var inputName = key;
var valueList;
valueList = $.cookies(cookieName).split(",");
for(i=0; i!=valueList.length;i++) {
var checkbox = $("input[name='filter-" + inputName +
"'][value='"+valueList[i]+"']");
checkbox.attr("checked","checked");
}
}
}
}
Upvotes: 1
Reputation: 10378
$.fn.userLocator = function(opts) {
var defaults = {
cookiename: ""// by default no cookie name if you pass with opts then it will extend in it
};
var options= $.extend({}, $.fn.userLocator.defaults, opts);
var tempname= options.cookiename.replace("user","");
if($.cookie(options.cookiename)){
var userLoc = [];
userLoc = $.cookie(options.cookiename).split(",");
for(i=0; i!=userLoc.length;i++) {
var checkbox = $("input[name='filter-'"+tempname+"][value='"+userLoc[i]+"']");
checkbox.attr("checked","checked");
}
}
}
at the time of call .userLocator ({ cookiename: "your cookie name" });
Upvotes: 0