jQuery: Is it possible to test both the input type and the attribute in a select...
source link: https://www.codesd.com/item/jquery-is-it-possible-to-test-both-the-input-type-and-the-attribute-in-a-selector.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
jQuery: Is it possible to test both the input type and the attribute in a selector?
I have a list of input
elements and using one selector I want to find those that
- are checkboxes
- 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.
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...
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK