2015-04-23 59 views
0

我有一个使用在DB的答案作为名称的IDS,以检查他们是否是正确的测验单选按钮。所以基本上我不能让它们成为同一个名字。使用jQuery选择/取消选择使用不同的名称

不管怎么说这给我留下了,可所有的检查,这是不是它应该如何工作的单选按钮。我发现jQuery允许单选按钮被取消选中,但我需要它们在您点击其他按钮时取消选中。

HTML:

<fieldset> 
    <input type="radio" name="21"> 
    <label for="21">Answer 21</label> 
    <input type="radio" name="22" class="checked"> 
    <label for="22">Answer 22</label> 
    <input type="radio" name="23" class=""> 
    <label for="23">Answer 23</label> 
    <input type="radio" name="24"> 
    <label for="24">Answer 24</label> 
</fieldset> 

脚本:

$("input[type='radio']").click(function (event) { 
    // If the button is selected. 
    if ($(this).hasClass("checked")) { 
     // Remove the placeholder. 
     $(this).removeClass("checked"); 
     // And remove the selection. 
     $(this).removeAttr("checked"); 
     // If the button is not selected. 
    } else { 
     // Remove the placeholder from the other buttons. 
     $("input[type='radio']").each(function() { 
      $(this).removeClass("checked"); 
     }); 
     // And add the placeholder to the button. 
     $(this).addClass("checked"); 
    } 
}); 

所以,如果21被选中,我点击22,21应取消

回答

0

如果你希望组相同的字段集内的收音机到像一个单选按钮组,那么你可以简单地做

$("input[type='radio']").click(function (event) { 
    $(this).addClass("checked");  
    $(this).siblings('input[type="radio"]').prop('checked', false).removeClass('checked') 
}); 

演示:Fiddle

+0

这也适用于Fieldset。对于正确答案的初始选择不适用于多个字段集。谢谢! – FranticJ3

0

使用单选按钮的值传递ID并给他们所有相同的名字。

<input type="radio" id="r21" value="21" name="radiobtns"> 
<label for="r21">21</label> 

然后你不需要jQuery。

0

试试这个代码,所有的单选按钮会取消选中,除了点击一个。像Aron P Johny说的那样,如果你想把所有的单选按钮与特定的问题和答案进行分组,那就用他的答案来代替。

$("input[type='radio']").click(function (event) {  
 
      $("input[type='radio']").prop('checked',false); 
 
      $(this).prop('checked',true);  
 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<fieldset> 
 
    <input type="radio" name="21"> 
 
    <label for="21">Answer 21</label> 
 
    <input type="radio" name="22" class="checked"> 
 
    <label for="22">Answer 22</label> 
 
    <input type="radio" name="23" class=""> 
 
    <label for="23">Answer 23</label> 
 
    <input type="radio" name="24"> 
 
    <label for="24">Answer 24</label> 
 
</fieldset>

+0

完美的作品。谢谢!! – FranticJ3

+0

欢迎并很高兴听到! –

+0

呃哦,看起来它会取消选择其他字段集中的其他问题。我们如何才能使它适用于多个字段集? – FranticJ3

0

So if 21 is checked and I click 22, 21 should uncheck如果这是你想你并不真的需要jQuery的..什么

<fieldset> 
<input type="radio" name="radio_button"> 
<label for="21">Answer 21</label> 
<input type="radio" name="radio_button" class="checked"> 
<label for="22">Answer 22</label> 
<input type="radio" name="radio_button" class=""> 
<label for="23">Answer 23</label> 
<input type="radio" name="radio_button"> 
<label for="24">Answer 24</label> 
</fieldset> 

只是确保它们都具有相同的名称..

+0

请注意,使用单选按钮的..只有1必须检查并另将取消选中..相比复选框,您可以检查它的倍数。 –