I’ve got an input with a class name of .aa_ant that contains the value 1.
Now, when I’m loading the page I’m doing this (CASE 1):
alert($('.aa_ant[value*=1]').length )
it outputs 1 as expected.
Now, I’m changing it to (CASE 2):
alert($('.aa_ant[value*="1"]').length )
It stops working. Also, if I change the 1 to a it also stops working (both CASES 1 and 2).
What I am doing wrong?
Update: the .aa_ant is a knockout control:
<input class='aa_ant' data-bind='value: aa_ant, readOnly: is_readonly' />
Could that be a problem ?
Update: With the length property I want to see if there are any input elements that contain that value (I don’t want any elements to have that value). Also, I know that I could get all .aa_ant elements and enumerate through them to see if anyone contains the value but I’d like to do it jquery-ish.
Update:
Here’s the actual solution for reference:
if($('.aa_ant').filter(function(index) {
if(this.value.indexOf("1") >=0) {
return true ;
}
return false ;
}).length>0 ) {
alert("Error");
}
Thanks for the help !
Your control doesn’t appear to have a
valueattribute. A CSS attribute selector won’t be able to read an attribute of an element if it isn’t set in the markup, that’s why it fails.This is a case of jQuery not actually complying exactly with the CSS spec as advertised. The only reason why
[value*=1]works regardless is because it’s not a valid CSS selector, so in modern browsers it skips the browser’s native Selectors API and uses jQuery’s selector engine instead, which does support unquoted numbers and can return based on thevalueproperty, even though thevalueattribute doesn’t appear in the markup, so you get the expected result. The other selectors[value*="1"],[value*=a]and[value*="a"]are all valid CSS, but won’t match your control because it doesn’t have avalueattribute in the markup, so you get no results.If you need to query an input control by its actual value, see if you can identify it by something else (does Knockout.js give it an ID?), otherwise you have to do some DOM traversal or filtering, and using
.val()to check its value in order to get the correct element. Selectors should only be used for querying based on static attributes (i.e. attributes that don’t usually change in value), not for dynamic ones likevalueforinputelements.A quick example using
.filter()and.val():