Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop over html table and get checked checkboxes (JQuery)

I have an HTML table with a checkbox in each row.
I want to loop over the table and see if there are any checkboxes that are checked.
The following does not work:

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

This prints in the console the following:

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

per row regardless of whether any checkbox is checked.

Update
Same issue with:

$('#mytable tr').each(function (i, row) {                                                                                                 
   var $actualrow = $(row);
    $checkbox = $actualrow.find(':checkbox:checked');
    console.log($checkbox);  
});
like image 673
Jim Avatar asked Aug 20 '13 09:08

Jim


Video Answer


2 Answers

Use this instead:

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

Let me explain you what the selector does: input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox After that: :checked will match all checked checkboxes.

You can loop over these checkboxes with:

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

Here is demo in JSFiddle.


And here is a demo which solves exactly your problem 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!');
        }
    });
});
like image 182
Minko Gechev Avatar answered Sep 30 '22 12:09

Minko Gechev


use .filter(':has(:checkbox:checked)' ie:

$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
 $('#out').append(this.id);
});
like image 28
suhailvs Avatar answered Sep 30 '22 11:09

suhailvs