2009-08-26 178 views
2

我正在处理一个长表单,它有几个单选按钮组。jQuery选择所有单选按钮组

在底部有一个单选按钮“不全”。当它被选中时,我想让所有的“N”单选按钮都被选中,但我无法使它工作。下面是代码的简化版本:

的jQuery:

$(document).ready(function(){ 
//initially hide the Remove All Questions 
$("div.#removeAllquest").hide(); 

//////////// Show Remove All Questions if radio button selected 
$("input.#RemoveAll").click(function() { 
    if ($(this).is(':checked')) 
    $("input:radio [class*='radioR']").attr("checked",true); 
    else 
$("input:radio [class*='radioR']").attr("checked",false); 
}); 

});

形式:

<table> 
    <tr> 
    <td>Y<input type="radio" name="row1" value="row1col1" class="q123col1"></td> 
    <td>N<input type="radio" name="row1" class="radioR" value="row1col2"></td> 
    <td>M<input type="radio" name="row1" value="row1col3" class="q123col3"></td> 
    </tr> 
    <tr> 
    <td>Y<input type="radio" name="row2" value="row2col1" class="q123col1"></td> 
    <td>N<input type="radio" name="row2" class="radioR" value="row2col2"></td> 
    <td>M<input type="radio" name="row2" value="row2col3" class="q123col3"></td> 
    </tr> 
    <tr> 
    <td>Y<input type="radio" name="row3" value="row3col1" class="q123col1"></td> 
    <td>N<input type="radio" name="row3" class="radioR" value="row3col2"></td> 
    <td>M<input type="radio" name="row3" value="row3col3" class="q123col3"></td> 
    </tr> 
    <tr> 
    <td colspan="2">No All </td> 
    <td> 
     <input name="RemoveAll" id="RemoveAll" type="radio" value="Y"> 
    </td> 
    </tr> 
</table> 

我在做什么错?

回答

11

这些都应该工作 - 第一个我试图保持你的风格。随着第二次,我改变了一下风格。在你的示例中,一旦他们被检查,没有真正的方法来取消选中他们。

$("input.#RemoveAll").click(function() { 
    if ($(this).is(':checked')) 
     $("input:radio.radioR").attr("checked", "checked"); 
    else 
     $("input:radio.radioR").removeAttr("checked"); 
}); 

$("#RemoveAll").click(function() { 
    if ($(this).is(':checked')) 
     $(".radioR").attr("checked", "checked"); 
    else 
     $(".radioR").removeAttr("checked"); 
}); 
+0

谢谢安迪!我用你的第一个选项,它像冠军一样工作。我想取消选中单选按钮......但是花了我很长时间才弄到这么远,我觉得现在有点超过我的头:) – Chnikki 2009-08-27 14:27:39

+0

我不认为你真的必须删除“checked”属性因为您无论如何都一次只能选择一个单选按钮,但其余代码看起来不错。 – 2010-08-24 16:11:10

1

首先,据我所知,只检查接受检查为XHTML中的有效值。因此,像下面应该做的伎俩

$("#RemoveAll").change(function() { 
    if ($(this).is(':checked')) 
      $("input:radio.radioR").attr("checked","checked"); 

    else 
      $("input:radio.radioR").removeAttr("checked"); 
    }); 
}); 

注意选择为删除更改所有单选按钮添加输入元素过滤器是不是真的有必要为$(“#ID”)调用的document.getElementById 。

1

这应该做你需要什么...

$("input.#RemoveAll").click(function() { 

    if ($(this).attr('checked') === "checked"){ 

    $("input:radio[class*='radioR']").attr("checked","checked"); 

    }else{ 

    $("input:radio[class*='radioR']").removeAttr("checked"); 

    } 
}); 

希望它能帮助,思南。