7

How do you reference a element in jquery BY NAME that has the [] 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 grab the element, but it does not work, I believe the [] in the name is messing it up, escaping it doesn't seem to work either. I can't figure out what I'm doing wrong

NakedBrunch
  • 48,713
  • 13
  • 73
  • 98
user384030
  • 199
  • 1
  • 3
  • 6
  • The HTML is incorrect. The only value the `multiple` attribute can take is `multiple`, `true` is an error. – Quentin Jan 05 '11 at 19:48
  • Issue is reproducible in Firefox 3.6.17+ For the bug pls refer to http://bugs.jquery.com/ticket/5482 – qwe May 05 '11 at 08:44

3 Answers3

10

One way is to quote the name in the selector:

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

Or:

$("[name='values[]']")
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
5

Related: How do I get jQuery to select elements with a . (period) in their ID?

Answer: Use double backslashes to escape the brackets.

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

Edit: Revised the example for validity's sake. Apparently, Sizzle isn't handling the unquoted version well.

Community
  • 1
  • 1
simshaun
  • 21,263
  • 1
  • 57
  • 73
0

It seems to work for me in Chrome.

If you run this code and look in the console you should 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>
sissonb
  • 3,730
  • 4
  • 27
  • 54