简体   繁体   English

使用jQuery在“名称”属性中带有“ []”括号时,如何预选单选按钮?

[英]How to pre-select radio group button when “name” attribute has “[]” brackets in it using jQuery?

If I remove the [ and ] in the name attribute this script works. 如果删除name属性中的[] ,则此脚本有效。 What am I doing wrong? 我究竟做错了什么? I want to post array to the backend so I'm using array syntax in the HTML. 我想将数组发布到后端,所以我在HTML中使用数组语法。

HTML: HTML:

<input type="radio" name="a[1]" id="1" value="0"/>
<label for="1">option1</label>

<input type="radio" name="a[1]" id="2" value="1"/>
<label for="2">option2</label>

<input type="radio" name="a[1]" id="3" value="2"/>
<label for="3">option3</label>

<input type="radio" name="a[1]" id="4" value="3"/>
<label for="4">option4</label>

JavaScript: JavaScript的:

<script>
    $(document).ready(function() {
        $("input[name=a[1]][value=" + 2 + "]").prop('checked', true);
    });
</script>

Put attribute value (ie a[1] in your case) in single quotes as shown below : 将属性值(在您的情况下为a[1] )放在单引号中,如下所示:

 <script>
    $(document).ready(function() {
        $("input[name='a[1]'][value=" + 2 + "]").prop('checked', true);
    });
 </script>

From the docs for attribute-equals-selector ... 文档的attribute-equals-selector ...

attribute An attribute name. attribute属性名称。

value An attribute value. value属性值。 Can be either an unquoted single word or a quoted string. 可以是未加引号的单个单词或带引号的字符串。

Since you have more than just a single word, it should be quoted. 由于您不仅有一个单词,所以应加引号。

Fiddle Demo 小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM