Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 Child" checkbox as well as the other checkboxes.

like image 262
Christoph Wurm Avatar asked Jan 18 '26 09:01

Christoph Wurm


1 Answers

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...

like image 106
Niklas Avatar answered Jan 19 '26 21:01

Niklas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!