簡體   English   中英

使用jQuery在“名稱”屬性中帶有“ []”括號時,如何預選單選按鈕?

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

如果刪除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>

文檔的attribute-equals-selector ...

attribute屬性名稱。

value屬性值。 可以是未加引號的單個單詞或帶引號的字符串。

由於您不僅有一個單詞,所以應加引號。

小提琴演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM