There are many textboxes (Django CharField) for which I am using tokenInput as the JS plugin for autocomplete feature. To intialize each of them, I need to set prepopulate with different tag values. I want to avoid following code duplication as shown below.
$("#id_tags_1").tokenInput("/xyz/tag_search/", {
theme: "facebook",
onAdd: function(item){
tag_ids.push(item.id);
$("#id_tag_domain").val(tag_ids.join(','));
},
onDelete: function(item){
tag_ids = _.without(tag_ids, item.id);
$("#id_tag_domain").val(tag_ids.join(','));
},
preventDuplicates: true,
tokenLimit: 3,
prePopulate: tags_val[0],
});
$("#id_tags_2").tokenInput("/xyz/tag_search/", {
theme: "facebook",
onAdd: function(item){
tag_ids.push(item.id);
$("#id_tag_domain").val(tag_ids.join(','));
},
onDelete: function(item){
tag_ids = _.without(tag_ids, item.id);
$("#id_tag_domain").val(tag_ids.join(','));
},
preventDuplicates: true,
tokenLimit: 3,
prePopulate: tags_val[1],
});
I came across another SO post where regular expression like this [^id_tags_] was suggested but I don't know how to select each tag value corresponding to different tags. I think part of the problem is that I don't know how to access the tag id else I could have split it and extracted the number. If there is any other elegant solution, please do suggest.
Right, you can select them with
$("[id^=id_tags_]")(an attribute-starts-with-selector). In the callbacks, if the plug-in is like standard plugins,thiswill refer to the element on which the original event causing the callback to occur was raised. So (again, if that plugin behaves in the normal way), within the callbacks,this.idshould be theidof the element on which the event occured. But I don't know that plugin, sometimes plugins pass that information in a different way.If that plugin doesn't provide access to the element on which the originating event occurred, you can still de-duplicate the code by using
eachand using the closure created by theeachiterator function to remember theid:In that, we create new
tagInputcallbacks for each element in theeachiterator function, and those are closures over the call to the iterator function, and so they have access to theidlocal variable (which will be specific to each call, and therefore to each element). If the term "closure" seems a bit alien, don't worry, closures are not complicated.