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

问题描述 投票:18回答:3

我有一个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);  
});
javascript jquery html
3个回答
54
投票

请改用:

$('#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!');
        }
    });
});

2
投票

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

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

1
投票
The following code snippet enables/disables a button depending on whether at least one checkbox on the page has been checked.
$('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的演示。

© www.soinside.com 2019 - 2024. All rights reserved.