tags:

views:

104

answers:

2

Is it possible to us jQuery to select a collection of form elements based on their value and/or state?

For instance, I have some code that looks like

jQuery("input[type='checkbox']").each(function(element){
    if(this.checked)
    {
         //do something with the checked checkeboxes
    }
});

I'd like to remove the interior conditional, and somehow add it to the initial selection. Either as part of the selector string, or via some additional method call on the chain.

+8  A: 

Specifically for the checked attribute, you can use the :checked selector:

var checkedInputs = $('input:checked');

For other attributes, you can use the attribute filters.

CMS
+1  A: 

Also for arbitrary filtering, use filter (as @CMS suggests). It's like grep but specifically for jQuery selection sets.

jQuery("input[type='checkbox']")
    .filter(function(){ return this.checked; })
    .each(function() {
        // Do something with "this"
    });
darkporter