2013-08-20 34 views
16

我有一个HTML表格,每行都有一个复选框。
我想遍历表格,看看是否有任何复选框被选中。
以下不工作:在html表格上循环并得到选中的复选框(jQuery)

$("#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); 
}); 
+3

是的,一个jQuery对象被打印到控制台,这是正常的。你有没有检查它的'长度'属性? –

+1

您是否试过'$ actualrow.find('input')。is(':checked');' –

+0

log'$ checkbox.length'。长度是否为零? –

回答

48

用这个代替:

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

让我解释一下,你有什么选择呢: input[type="checkbox"]意味着这将匹配每个<input />与类型属性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!'); 
     } 
    }); 
}); 
+0

我想单独获取。如果复选框被选中,但同一行中的文本框未被填充,我想显示一个提醒 – Jim

+0

好的,让我给你一个例子。 –

+0

@Jim检查这个解决方案http://jsfiddle.net/DuE8K/1/ –

-1

在您的代码中是缺少});

$("#save").click(function() { 
    $('#mytable tr').each(function (i, row) { 
     var $actualrow = $(row); 
     $checkbox = $actualrow.find('input:checked'); 
     console.log($checkbox); 
    }); 
}); 
0
下面的代码片段启用取决于是否在页面上至少一个复选框被选中/禁用按钮。
$('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

相关问题