循环遍历html表并获取选中的复选框(JQuery)

我有一个HTML表,每行都有一个复选框。
我想循环遍历表,看看是否有任何复选框被选中。
以下不起作用:

$("#save").click( function() { $('#mytable tr').each(function (i, row) { var $actualrow = $(row); checkbox = $actualrow.find('input:checked'); console.log($checkbox); }); 

这将在控制台中打印以下内容:

[prevObject: jQuery.fn.jQuery.init[1], context: tr, selector: "input:checked", constructor: function, init: function…]

每行,无论是否选中任何复选框。

更新
同样的问题:

 $('#mytable tr').each(function (i, row) { var $actualrow = $(row); $checkbox = $actualrow.find(':checkbox:checked'); console.log($checkbox); }); 

改为使用它:

 $('#save').click(function () { $('#mytable').find('input[type="checkbox"]:checked') //... }); 

让我解释一下选择器的作用: input[type="checkbox"]意味着这将匹配每个类型属性type等于checkbox之后:checked将匹配所有选中的复选框。

您可以使用以下方法遍历这些复选框:

 $('#save').click(function () { $('#mytable').find('input[type="checkbox"]:checked').each(function () { //this is the current checkbox }); }); 

这是JSFiddle的演示。


这是一个演示,它完全解决了你的问题http://jsfiddle.net/DuE8K/1/ 。

 $('#save').click(function () { $('#mytable').find('tr').each(function () { var row = $(this); if (row.find('input[type="checkbox"]').is(':checked') && row.find('textarea').val().length <= 0) { alert('You must fill the text area!'); } }); }); 

使用.filter(':has(:checkbox:checked)'即:

 $('#mytable tr').filter(':has(:checkbox:checked)').each(function() { $('#out').append(this.id); }); 

以下代码段启用/禁用按钮,具体取决于是否已选中页面上的至少一个复选框。

 $('input[type=checkbox]').change(function () { $('#test > tbody tr').each(function () { if ($('input[type=checkbox]').is(':checked')) { $('#btnexcellSelect').removeAttr('disabled'); } else { $('#btnexcellSelect').attr('disabled', 'disabled'); } if ($(this).is(':checked')){ console.log( $(this).attr('id')); }else{ console.log($(this).attr('id')); } }); }); 

这是JSFiddle的演示。

在你的代码中是一个}); 失踪。

 $("#save").click(function() { $('#mytable tr').each(function (i, row) { var $actualrow = $(row); $checkbox = $actualrow.find('input:checked'); console.log($checkbox); }); });