Search code examples
jqueryjquery-selectorsjquery-filter

jQuery .filter() method doesn't return elements as expected in jQuery 1.5.1


The names of some of my HTML inputs contain multiple square brackets.

E.g.

<input name="skus[0].skuattributeoptions[1].sao_option_id" value="559" />

I have read that you can have attribute values with square brackets so long as you enclose the value in quotes. Which is fine but, when I use .filter() on a jquery object that contains elements with a name like the above, no elements are returned.

Below is a screenshot of the output from Chrome's console that illustrates what I mean.

inputs = $('[name="skus[0].skuattributeoptions[1].sao_option_id"]') returns three elements as expected.

But when I use inputs.filter('[name="skus[0].skuattributeoptions[1].sao_option_id"]') on that same bunch of elements I get nothing returned.

Please note that when the selector passed into .filter() has only one set of square brackets, E.g. inputs.filter('[name*="skuattributeoptions[1].sao_option_id"]') the filter returns what I expected!

I am using jQuery 1.5.1. Am I doing something wrong?

http://www.photogifts.co.uk/content/images/affiliate/example/jquery-filter-issue.png


Solution

  • That's correct, I just tried it using jQuery 1.5.1 and it returned an empty set [], I would recommend updating the jQuery, if you have to use it, you can read the name properties instead:

    inputs.filter(function() {
       return this.name === "skus[0].skuattributeoptions[1].sao_option_id";
    });
    

    http://jsfiddle.net/zVUNm/

    Edit: And it also work if you escape the [, ] and . characters instead of using quotes, it seems there is a bug in jQuery 1.5.1's .filter() method:

    inputs.filter('[name=skus\\[0\\]\\.skuattributeoptions\\[1\\]\\.sao_option_id]'); 
    

    http://jsfiddle.net/tE4et/

    Well, that version is an old one, it had been released in February of 2011 and this problem doesn't exist in newer versions.