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');

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!