JQuery - 每行启用/禁用复选框

时间:2012-01-27 05:53:19

标签: jquery

我有一个查询,它返回一个可用服务的表列表,每个返回服务的表行都有3个复选框 - Book,Send Info,No Thanks。

echo '<td align="center">'.'<input type="checkbox" id="ckBook_'.$i.'"  name="ckBook['.$i.']"></input>'.'</td>';
echo '<td align="center">'.'<input type="checkbox"  id="ckSendInfo_'.$i.'" name="ckSendInfo['.$i.']" class="group1_'.$i.'"></input>'.'</td>';
echo '<td align="center">'.'<input type="checkbox" id="ckNoThanks_"  name="ckNoThanks['.$i.']" class="group1_'.$i.'"></input>'.'</td>';

如果用户单击其中一行中的某个复选框,则应禁用同一行中的其他复选框,否则应启用它们。我尝试过使用单选按钮,但是Book复选框也在底部返回一个运行总计,当我使用单选按钮时,它会混淆总计功能。

我研究过并认为我非常接近解决方案。我修改了我在此站点上找到的一些代码,但它当前仅在选中第一列复选框(任何行)时影响第二列和第三列。

$(function() {
 enable_cb();
 $('input[id^=ckBook_]').click(enable_cb);
 $('input[id^=ckSendInfo_]').click(enable_cb);
 $('input[id^=ckNoThanks_]').click(enable_cb);
});

function enable_cb() {
 if (this.checked) 
  {
     $("input.group1_0").attr("disabled", true);
  }   

 else
   {
    $("input.group1_0").removeAttr("disabled");
     $("input.group1_1").removeAttr("disabled");
  }

}

2 个答案:

答案 0 :(得分:2)

这个简单的代码可以做到:

// bind a click handler on any of those checkboxes
// withint the table #tableID
$('input[type=checkbox]', '#tableID').click(function(e) {

    // 'this' is the clicked checkbox
    $(this).closest('tr')
        // go to the TR parent and find all checkboxes,
        // but exclude myself with .not()
        .find('input[type=checkbox]').not(this)
        // use .prop() to set special attributes like disabled
        .prop('disabled', this.checked);

});

<强> DEMO

进一步阅读:

答案 1 :(得分:1)

试试这个

function enable_cb() {
   if ($(this).is(':checked')){
         $("input.group1_0").attr("disabled", true);
      }else{
        $("input.group1_0").attr("disabled", false);
        $("input.group1_1").attr("disabled", false);
      }  
    }

<强>更新

$(':checkbox').click(function(){
   var elems = $(this).parents('tr').find(':checkbox');
   elems.not($(this)).attr('disabled',$(this).is(':checked'));
});
相关问题