如果选择了另一个,则取消选择单选按钮

时间:2011-08-28 16:02:29

标签: jquery radio-button

考虑以下标记:

<form>

<div class="project">
<ul class="choice">
    <li><label for="firstchoice_1">First choice</label><input type="radio" name="firstchoice" value="1" id="firstchoice_1" /></li>
    <li><label for="secondchoice_1">Second choice</label><input type="radio" name="secondchoice" value="1" id="secondchoice_1" /></li>
</ul>
</div>

<div class="project">
<ul class="choice">
    <li><label for="firstchoice_2">First choice</label><input type="radio" name="firstchoice" value="2" id="firstchoice_2" /></li>
    <li><label for="secondchoice_2">Second choice</label><input type="radio" name="secondchoice" value="2" id="secondchoice_2" /></li>
</ul>
</div>

</form>

我想要做的是,如果每个.project组中的单选按钮被选中,则禁用一个(因此每个组中只能选择First choiceSecond choice )。我知道怎么做是在一个特定情况下禁用一个特定的单选按钮,但我不知道如何概括它,因为它们可能是一百个这样的.project组。

修改:请注意,只能选择整个First choice(反之亦然)。该名称已经使用了相同的名称。在整个标记中使用相同的name属性。只有两个不同的name s。

6 个答案:

答案 0 :(得分:10)

只需向他们提供相同的name但不同的value s;这将自动发生,因为这是单选按钮的设计方式。

答案 1 :(得分:2)

您必须在所有单选按钮上收听更改事件。当其中任何一个发生变化时,您将检查是否已检查。如果是,您将取消选中.project中的所有其他单选按钮:

$('input[type=radio]').change(function()
{
    if (this.checked)
    {
        $(this).closest('.project')
            .find('input[type=radio]').not(this)
            .prop('checked', false);
    }
});

答案 2 :(得分:2)

如果您将相同的name提供给一组单选按钮,则只要您点击它们,它们就会自动检查/取消选中。但是对于每个没有标记的单选按钮,ID应该是唯一的。看看这个工作演示,我希望这是你正在寻找的。

正在使用 demo

答案 3 :(得分:0)

您只需对组中的所有按钮使用相同的名称。然后浏览器自动禁用。

答案 4 :(得分:0)

&#13;
&#13;
 $(function(){
 if($(this).attr('checked')==true)
    {
        $('.project').not(this).attr('checked',false);
    }
    });
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>

<div class="project">
<ul class="choice">
    <li><label for="firstchoice_1">First choice</label><input type="radio" name="firstchoice" value="1" id="firstchoice_1" /></li>
    <li><label for="secondchoice_1">Second choice</label><input type="radio" name="secondchoice" value="1" id="secondchoice_1" /></li>
</ul>
</div>

<div class="project">
<ul class="choice">
    <li><label for="firstchoice_2">First choice</label><input type="radio" name="firstchoice" value="2" id="firstchoice_2" /></li>
    <li><label for="secondchoice_2">Second choice</label><input type="radio" name="secondchoice" value="2" id="secondchoice_2" /></li>
</ul>
</div>

</form>
&#13;
&#13;
&#13;

或者如果您对多个元素使用相同的名称,那么您可以选择其中一个。

答案 5 :(得分:-1)

您只需对组中的所有按钮使用相同的名称。然后浏览器自动禁用。

如果你想要

,你可以改变不同值的id
相关问题