如何使用.nextAll()(或其他方法)清除当前的其他无线电输入

时间:2013-04-26 15:43:50

标签: jquery

JSFiddle

我希望能够清除所有单选按钮,这些按钮是我父div下载的兄弟。例如,如果选择单选按钮选项2的选项1,我想清除单选按钮选择3和单选按钮选择4中的值。

$('input:radio[name=radio-choice-2]').change(
    function () {
        if ($(this).val() == 'choice-1') {
            $(this).parent().nextAll('div :radio').removeAttr('checked');
        }   
    });
<form method="post" action="">
    <div id="question-1">
         <h4>Radio Button Choice 1</h4>

        <label for="radio-choice-1-a" class="checkbox inline">Choice 1
            <input type="radio" name="radio-choice-1" id="radio-choice-1-a" tabindex="2" value="choice-1" />
        </label>
        <label for="radio-choice-1-b" class="checkbox inline">Choice 2
            <input type="radio" name="radio-choice-1" id="radio-choice-1-b" tabindex="3" value="choice-2" />
        </label>
    </div>
    <div id="question-2" class="collapse-group">
         <h4>Radio Button Choice 2</h4>

        <label for="radio-choice-2-a">Choice 1</label>
        <input type="radio" name="radio-choice-2" id="radio-choice-2-a" tabindex="2" value="choice-1" />
        <label for="radio-choice-2-b">Choice 2</label>
        <input type="radio" name="radio-choice-2" id="radio-choice-2-b" tabindex="3" value="choice-2" />
    </div>
    <div id="question-3" class="collapse-group">
         <h4>Radio Button Choice 3</h4>

        <label for="radio-choice-3-a">Choice 1</label>
        <input type="radio" name="radio-choice-3" id="radio-choice-3-a" tabindex="2" value="choice-1" checked />
        <label for="radio-choice-3-b">Choice 2</label>
        <input type="radio" name="radio-choice-3" id="radio-choice-3-b" tabindex="3" value="choice-2" />
    </div>
    <div id="question-4" class="collapse-group">
         <h4>Radio Button Choice 4</h4>

        <label for="radio-choice-4-a">Choice 1</label>
        <input type="radio" name="radio-choice-4" id="radio-choice-4-a" tabindex="2" value="choice-1" checked />
        <label for="radio-choice-4-b">Choice 2</label>
        <input type="radio" name="radio-choice-4" id="radio-choice-4-b" tabindex="3" value="choice-2" />
    </div>
</form>

3 个答案:

答案 0 :(得分:1)

尝试

$('input:radio').change(function () {   
   $(this).closest('div[id^="question"]').nextAll('div[id^="question"]').find(':radio').prop('checked', false)
});

演示:Fiddle

答案 1 :(得分:0)

$('input:radio').change(function () {
    $(this).parents('div').nextAll('div').each(function () {
        $(this).find(':input').prop('checked',false);
    });
});

<强> jsFiddle example

答案 2 :(得分:0)

所以问题是使用传统的DOM遍历方法,你需要向上,然后向上,然后向下 - 但是这个功能并不是真正的上下内容。你想要的是将DOM看作一个线性序列,然后选择所讨论的所有单选按钮 - 无论它们是如何嵌套的。

我刚才写了一个插件:jQuery sequential traversal

使用此功能,获取您所使用的无线电的代码如下:

$(this).sequentialNextAll(':radio').removeAttr('checked');

I forked your fiddle表示它与原作的差异很小。