如何使用jquery为可点击表格单元格中的单选按钮切换“已选中”?

时间:2012-07-19 20:20:26

标签: jquery radio-button

我有几种形式,在表格中嵌入了单选按钮和复选框。我想两个使用jquery做两件事:

  • 首先,用户可以通过单击包含按钮的表格单元格“单击”单选按钮或复选框。

  • 其次,用户可以通过点击两次切换复选框单选按钮。因此,单击已经检查过的单选按钮(或包含它的单元格)应取消 - 检查它,不要在组中选择任何单选按钮。

我可以单独做这两件事,但我坚持让他们一起工作。请帮忙!

这是我不太常用的jquery代码:

$(".clickable", Q)
    .mouseover( function(){ $(this).addClass('mouseover-cell'); })
    .mouseout( function(){ $(this).removeClass('mouseover-cell'); })
    .click( function(event){
        if( event.target.type != 'checkbox' && event.target.type != 'radio' ){
            var x = $('input', this).attr("checked");
            $('input', this).attr("checked", !x);

            //$('input', this).trigger("click");
        }
        return false;
    });

单个按钮的html看起来像这样:

<tr>
  <td>
    Label for the button group
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="1">
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="2">
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="3">
  </td>
</tr>

1 个答案:

答案 0 :(得分:2)

您的代码工作正常,布局略有不同。

你可以在这里测试一下

Clickable cells

$(".clickable").mouseover( function(){ $(this).addClass('mouseover-cell'); });
$(".clickable").mouseout( function(){ $(this).removeClass('mouseover-cell'); });
$(".clickable").click( function(event){
    if( event.target.type != 'checkbox' && event.target.type != 'radio' ){
        var x = $('input', this).attr("checked");
        $('input', this).attr("checked", !x);
    }
    return false;
});​

<table border="1">
<tr>
  <td>
    Label for the button group
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="1">
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="2">
  </td>
  <td class="clickable">
    <input type="radio" name="q1" value="3">
  </td>
</tr>
</table>​
相关问题