Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference an element by name with [] brackets in it? [duplicate]

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

like image 805
user384030 Avatar asked Jan 05 '11 19:01

user384030


People also ask

Can HTML ID have brackets?

An id cannot include square brackets. It is forbidden by the spec. Some browsers might error correct and cope, but you should fix you data instead of trying to deal with bad data.

What do square brackets mean in JavaScript?

Creating arrays in JavaScript is easy with the array literal notation. It consists of two square brackets that wrap optional array elements separated by a comma. Array elements can be any type, including number, string, boolean, null, undefined, object, function, regular expression and other arrays.


2 Answers

One way is to quote the name in the selector:

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

Or:

$("[name='values[]']")
like image 182
Frédéric Hamidi Avatar answered Oct 23 '22 15:10

Frédéric Hamidi


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.

like image 42
simshaun Avatar answered Oct 23 '22 14:10

simshaun