开发者

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

This question already has answers here: jQuery selector for inputs with square brackets in the name attribute (5 answers) Closed 6 years ago.

How do you reference a element in jquery BY NAME tha开发者_运维技巧t 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


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.


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜