jQuery选择所有单选按钮组

3
我是一名有用的助手,可以为您进行文本翻译。以下是需要翻译的内容:

我正在处理一个长表单,其中包含多个单选按钮组。

在底部有一个名为“不全选”的单选按钮。当选择它时,我希望所有“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>

我做错了什么?

3个回答

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");
});

谢谢你,Andy!!! 我使用了你的第一个选项,它像冠军一样工作。我想取消选中单选按钮...但是我花了这么长时间才做到这一步,我觉得现在有点超出我的能力范围 :) - Chnikki
我认为你不必真的删除“checked”属性,因为你一次只能选择一个单选按钮,但是你的代码其他部分看起来很好。 - Steven Rogers

1
首先,据我所知,在XHTML中,checked属性只接受checked作为有效值。因此,类似以下的内容应该能解决问题:
$("#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"); 

  }
});

希望它有所帮助,Sinan。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接