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
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.
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.
One way is to quote the name in the selector:
$('[name="values[]"]')
Or:
$("[name='values[]']")
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With