簡體   English   中英

使用“全選”選項選擇多個單選按鈕

[英]Selecting multiple radio buttons with “Select All” option

我有一個向用戶顯示單選按鈕列表的表單。 還有一個選項可以選擇特定列中的所有按鈕。 選擇第一次可以正常工作,但是當我想在兩者之間來回切換時,它會中斷。

如何僅單擊一下就可以選擇單列中的所有單選按鈕?

 function checkAll(e) { if (e.hasClass('allFirst')) { $('.first').attr('checked', 'checked'); } else { $('.second').attr('checked', 'checked'); } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <input type="radio" name="A" class="first" />1</td> <td> <input type="radio" name="A" class="second" />2</td> </tr> <tr> <td> <input type="radio" name="B" class="first" />1</td> <td> <input type="radio" name="B" class="second" />2</td> </tr> <tr> <td> <input type="radio" name="C" class="first" />1</td> <td> <input type="radio" name="C" class="second" />2</td> </tr> </table> <input type="radio" name="all" class="allFirst" onclick="checkAll($(this));" />Select All #1 <input type="radio" name="all" class="allSecond" onclick="checkAll($(this));" />Select All #2 

如果“全選#1”,然后“全選2”,然后再次選擇“全選1”,則第三次嘗試將不會選中單選按鈕。

https://jsfiddle.net/jb7gfev9/

嘗試將attr更改為prop

有關更多信息,請參見此問題

您需要使用jquery .prop()而不是.attr()

 function checkAll(e) { if (e.hasClass('allFirst')) $('.first').prop('checked', true); else $('.second').prop('checked', true); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <input type="radio" name="A" class="first" />1</td> <td> <input type="radio" name="A" class="second" />2</td> </tr> <tr> <td> <input type="radio" name="B" class="first" />1</td> <td> <input type="radio" name="B" class="second" />2</td> </tr> <tr> <td> <input type="radio" name="C" class="first" />1</td> <td> <input type="radio" name="C" class="second" />2</td> </tr> </table> <input type="radio" name="all" class="allFirst" onclick="checkAll($(this));" />Select All #1 <input type="radio" name="all" class="allSecond" onclick="checkAll($(this));" />Select All #2 

只是為Mohammad的答案添加了一些上下文,在這種情況下,.attr()適用於默認狀態,而.prop()適用於DOM樹的當前狀態,因此其值在此處進行切換。 如果您的用戶可以更新屬性值,則需要使用.prop()來獲取當前值。

暫無
暫無

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

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