如何预先选择无线电组按钮时;name”;属性具有“;[]”;使用jQuery

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

本文关键字:jQuery 使用 属性 name 选择 何预先 无线电 按钮      更新时间:2023-09-26

如果删除name属性中的[],此脚本就可以工作。我做错了什么?我想将数组发布到后端,所以我在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:

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

将属性值(即a[1])放在单引号中,如下所示:

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

从属性等于选择器的文档

属性属性名称。

value属性值。可以是未加引号的单个单词,也可以是带引号的字符串。

既然你不仅仅有一个单词,就应该引用它。

Fiddle演示