Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery eq function unexpected behavior

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:

enter image description here

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?

like image 530
dmgig Avatar asked Aug 17 '15 15:08

dmgig


2 Answers

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.

like image 131
dfsq Avatar answered Oct 31 '22 21:10

dfsq


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.

like image 4
davcs86 Avatar answered Oct 31 '22 21:10

davcs86