How to associate an element by name with [] brackets in it?

How do you reference an element in jquery BY NAME that has [] in it.

<select name="values[]" multiple="true"> <option value="1">1</option> <option value="2">2</option> <option value="2">2</option> </select> <script type="text/javascript"> $('[name=values[]]'); </script> 

this should capture the element, but it wonโ€™t work, I believe that [] in the title will spoil it, avoiding it does not seem to work either. I cannot understand what I am doing wrong.

+7
source share
4 answers

One way is to specify a name in the selector:

 $('[name="values[]"]') 

Or:

 $("[name='values[]']") 
+8
source

Related: How do I get jQuery to select items using. (period) in their ID?

Answer: Use double backslash to avoid parentheses.

$('[name="values[]"]');

Edit: revised usage example. Sizzle doesnโ€™t seem to handle the unquoted version well.

+5
source

Have you used double backslash? Only one will not do this, as JavaScript will turn \[ into [ before jQuery sees it.

0
source

This seems to work for me in Chrome.

If you run this code and look in the console, you will see the elements

 <select name="values[]" multiple="true"> <option value="1">1</option> <option value="2">2</option> <option value="2">2</option> </select> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> // all the inputs with the name value console.log($('[name=values[]]')); // The first input with the name value console.log($('[name=values[]]')[0]); </script> 
0
source

All Articles