Jim Jim - 16 days ago 5
HTML Question

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);
});

Answer

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!');
        }
    });
});
Comments