I found a bug in a program I had written, but the behavior of the error is inexplicable to me:
If I have:
<input type="text" name="cust_id" value="666" />
<input type="text" name="phone[]" value="666" />
And then use this selector:
var test = $("input[name=phone[]]:eq(0)");
test.css("color", "red");
I see this:
What I'm surprised by is the fact that the eq(0)
selects the first input even though I explicitly tell it to find only ones with name=phone[]
Here is a fiddle: https://jsfiddle.net/1xdnv1t8/
Is this expected behavior? Does the eq selector ignore attribute selectors?
You need to quote name attribute:
var test = $("input[name='phone[]']:eq(0)");
because phone[]
is not valid name without quotes. So jQuery parser (or DOM) simply ignores everything invalid and treats selector as if it was simply input[name='phone']:eq(0)
. Also worth noting, that looks like this behaviour is fixed in more up to date versions of jQuery. You use pretty old 1.6.4 in your demo, but if you check it with 1.8.x
and above it will work properly throwing error.
For example, if you try
try {
document.querySelector("input[name=phone[]]")
}
catch(e) {
alert(e.message)
}
it will even throw an error
Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document': 'input[name=phone[]]' is not a valid selector.
But jQuery is more forgiving and it just selects whatever it can.
Use
var test = $("input[name='phone[]']:eq(0)");
JSFiddle
In the selector especification states
jQuery( "[attribute='value']" )
attribute: An attribute name.
value: An attribute value. Can be either an unquoted single word or a quoted string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With