使用jQuery禁用表格内的所有复选框

12

当单击表格内的超链接时,我需要禁用表格单元格内的所有复选框。

我正在使用以下 jQuery 代码来选择嵌套在表格中的所有复选框。

$el = $(this).parents('table:eq(0)')[0].children('input[type="checkbox"]');
$($el).attr('checked', true);

由于某些原因,这段代码不起作用。

有人能给我展示如何修复它吗?

7个回答

34
$('table input[type=checkbox]').attr('disabled','true');

如果你有一张表的ID

$('table#ID input[type=checkbox]').attr('disabled','true');

3
我注意到应该写成true而不是'true'。这个可以正常工作:$('table input[type=checkbox]').attr('disabled',true) ,但这个不行:$('table input[type=checkbox]').attr('disabled','true')。 - gpasse
帮助了我并使我免于编写问题。谢谢。+1 - SearchForKnowledge

6

禁用?

$("a.clickme").click(function(){
  $(this)                    // Link has been clicked
    .closest("td")           // Get Parent TD
    .find("input:checkbox")  // Find all checkboxes
    .attr("disabled", true); // Disable them
});

或者选中?
$("a.clickme").click(function(){
  $(this)                    // Link has been clicked
    .closest("td")           // Get Parent TD
    .find("input:checkbox")  // Find all checkboxes
    .attr("checked", false); // Uncheck them
});

2
你的代码可以更简单:

你的代码可以更加简洁:

$el = $(this).parents('table:eq(0)')[0].children('input[type="checkbox"]');

可能是:

$el = $(this).parents('table:first :checkbox');

然后要禁用它们:

$el.attr('disabled', 'disabled');

或者检查它们:

$el.attr('checked', 'checked');

或者取消勾选它们:

$el.removeAttr('checked');

或者启用它们:
$el.removeAttr('disabled');

0

另请参阅:选择器/复选框

jQuery("#hyperlink").click(function() {
  jQuery('#table input:checkbox').attr('disabled', true);
  return false;
});

0

// 启用/禁用所有复选框

$('#checkbox').click(function() {

    var checked = $(this).attr('checked');
    var checkboxes = '.checkboxes input[type=checkbox]';

    if (checked) {
        $(this).attr('checked','checked');
        $(checkboxes).attr('disabled','true');
    } else {
        $(this).removeAttr('checked');
        $(checkboxes).removeAttr('disabled');
    }
});

0

------------------------------- 下面是 HTML 代码 ------------------------------

<table id="myTable">
    <tr>
        <td><input type="checkbox" checked="checked" /></td>
        <td><input type="checkbox" checked="checked" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
</table>

<input type="button" onclick="callFunction()" value="Click" />

-------------------------------以下是JQuery代码-------------------------------

    <script type="text/javascript">
    function callFunction() {
        //:
        $('table input[type=checkbox]').attr('disabled', 'true');
    }
</script>

嗨,在点击按钮之后,您将看到当此JS函数被调用时,所有四个复选框都将变为禁用状态。谢谢。 - Raja Danish

0

这是我的解决方案

// Action sur le checkbox
        $("#tabEmployes thead tr th:first input:checkbox").click(function() {
            var checked = $(this).prop('checked');
            $("#tabEmployes tbody tr td:first-child input:checkbox").each(function() {
                $(this).prop('checked',checked);
            });
        });

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