April 23, 2012
Can a jQuery selector find elements based on their data?
Question by Codemonkey
I have an application with a considerable amount of checkboxes. Each of them has a jQuery data parameter indicating which group they belong to, e.g. <input type="checkbox" class="show" data-group="zones" />
In some cases I would like to select a subset of these checkboxes based on the data they contain. Can a jQuery selector pull this of? If not, are there any other ways of doing this short of manually filtering?
Answer by Starx
After researching a bit, There is also another way, using filter()
var inputs = $('input').filter(function() {
return $(this).data("groups") == true
});
Next manipulate as a whole
inputs.each(function() {
$(this).data('groups', 'new zone');
});
Or you modify the single element
inputs[0].data('groups', 'new zone');