“Imagination is everything. It is the preview of life's coming attractions”

- Albert Einstein

  • How to select input with array name attribute in jQuery above version 1.4.x


    How to select input with array name attribute in jQuery above 1.4

    Recently I’ve been working on some simple web page. Not much of a big deal, it contained mostly plain html with a bit of Php and JavaScript. Only one JavaScript framework was attached, and that was jQuery version 1.4.x. I was going to work on this site for a bit longer, so I said to myself “time for some updates”. And then I did it - replaced ye old 1.4.x release with fresh and shiny version 1.8.2. That’s when gates of hell opened - some of formerly working form validators suddenly broke - and the question was why?

    I started to browse small script that was attached to the page and found the culprit. Situation I encountered is shown on image below.

    A bit buggy selection

    As we can see here, selecting all nodes that contain attribute name=test[] is not accepted in jQuery 1.5.x and above. And that’s the way it should be according to jQuery API. Lower version were too tolerant about this. Image below shows the right way to select these nodes.

    The proper way

    First method using $(‘[name=”test[]”]’) (also replacable by $(“[name=’test[]’]”)) is done “by the book” just as jQuery API shows. The second one - $(“[name=”test[]”]”) - can be used when you really want to stick to double quotes all the time - quotes surrounding test[] are escaped here. I recommend used the first selector, because the second seems to be like not enough badass for a real coder.

    Back