jQuery selector for inputs with square brackets in the name attribute

JavascriptJqueryInputJquery Selectors

Javascript Problem Overview


I'm trying to select this element which has square brackets in the name attribute:

<input type="text" name="inputName[]" value="someValue">

I've tried this (which doesn't work):

$('input[inputName[]=someValue]')

and neither does this:

$('input[inputName&#91;&#93;=someValue]')

or this:

$('input["inputName[]"=someValue]')

EDIT: As some of you have pointed out, $('input[inputName=someValue]') would never work. What I was trying to do was: $('input[name=inputName][value=someValue]'). (But with [] in the name attribute).

Javascript Solutions


Solution 1 - Javascript

Per the jQuery documentation, try this:

$('input[inputName\\[\\]=someValue]')

[EDIT] However, I'm not sure that's the right syntax for your selector. You probably want:

$('input[name="inputName[]"][value="someValue"]')

Solution 2 - Javascript

You can use backslash to quote "funny" characters in your jQuery selectors:

$('#input\\[23\\]')

For attribute values, you can use quotes:

$('input[name="weirdName[23]"]')

Now, I'm a little confused by your example; what exactly does your HTML look like? Where does the string "inputName" show up, in particular?

edit fixed bogosity; thanks @Dancrumb

Solution 3 - Javascript

The attribute selector syntax is [name=value] where name is the attribute name and value is the attribute value.

So if you want to select all input elements with the attribute name having the value inputName[]:

$('input[name="inputName[]"]')

And if you want to check for two attributes (here: name and value):

$('input[name="inputName[]"][value=someValue]')

Solution 4 - Javascript

If the selector is contained within a variable, the code below may be helpful:

selector_name = $this.attr('name');
//selector_name = users[0][first:name]

escaped_selector_name = selector_name.replace(/(:|\.|\[|\])/g,'\\$1');
//escaped_selector_name = users\\[0\\]\\[first\\:name\\]

In this case we prefix all special characters with double backslash.

Solution 5 - Javascript

Just separate it with different quotes:

<input name="myName[1][data]" value="myValue">

JQuery:

var value = $('input[name="myName[1][data]"]').val();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionaidanView Question on Stackoverflow
Solution 1 - JavascriptDancrumbView Answer on Stackoverflow
Solution 2 - JavascriptPointyView Answer on Stackoverflow
Solution 3 - JavascriptGumboView Answer on Stackoverflow
Solution 4 - JavascriptEric KigathiView Answer on Stackoverflow
Solution 5 - Javascriptslva2000View Answer on Stackoverflow