开发者

jQuery: Is it possible to test for both input type and and attribute in one selector?

I have a list of input elements and using one selector I want to find those that

  1. are checkboxes
  2. have the value attribute set

Can I do that?

I tried:

  • $(items).find("input:checkbox[value]")
  • $(items).find("input[value]:checkbox")

But both ignore the [value] and only test for input:checkbox.

Sure, I can use two selectors, but just one would be nicer.


My essential use case is this.

Basically, I want to take some action on a checkbox based on whether other checkboxes are unchecked or not. In this example the "parent" checkbox is still checked because the jQuery selector "input[value]:checkbox" in function getChildrenCheckboxes matches the "No Chi开发者_运维问答ld" checkbox as well as the other checkboxes.


Firstly, if people take the time to provide you with answers, you could at least take the effort in accepting those answers.

Secondly, regarding your question you can either use filter() or check whether value is empty:

$('input[value!=""]:checkbox').addClass('selected');

http://jsfiddle.net/niklasvh/pEK3c/

or

$('input:checkbox').filter(function(){
 return this.value.length;   
}).addClass('selected');

example: http://jsfiddle.net/niklasvh/duAB8/

edit

Regarding the question why not just use $('input[value]') to check the presence of a value, firstly it depends whether you want to know whether its empty, or not there at all, and secondly, and perhaps most importantly, do you want it to work consistently over different browsers?

The following markup:

<input type="checkbox" value="2" />
<input type="checkbox" value="" />
<input type="checkbox"  />
<input type="checkbox" value="23" title="a" />

With the following selector:

$('input:[value]:checkbox').prop('checked',true);

Will give the following results:

Chrome 11, X - - X
FF4,       X - X X
IE 8,      X - X X

So are you interested in knowing whether the attribute is defined, or whether its empty? If the first one, you can expect differentiating results for that selector. Where as the 2 first examples both give consistent results for X - - X.

It'd be quite a different story if you'd be looking for the [title] attribute...


EDIT:

If you want elements that are checkboxes AND have the value attribute, you can leverage the multiple attribute selector: http://api.jquery.com/multiple-attribute-selector/

$("input[type='checkbox'][value]")
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜