开发者

Using jQuery selectors to get form elements based on value or state

开发者 https://www.devze.com 2022-12-11 20:15 出处:网络
Is it possible to us jQuery to select a collection of form elements based on their value and/or state?

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, an开发者_运维知识库d somehow add it to the initial selection. Either as part of the selector string, or via some additional method call on the chain.


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

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

For other attributes, you can use the attribute filters.


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"
    });
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号