Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop through html table and check if a checkbox is checked or not

What I'm trying to do here is validating HTML table. I need at least one checkbox to be checked before proceeding. It's doing what it's need to do, except when I don't check a checkbox.

It loops the alert "nothing found" by the count of data on the HTML table. How can I make it better? I need to loop inside the table to get the data on the same row with the checkbox checked.

JS

$('#dataTable').find('tr').each(function () {
    var row = $(this);
    if (row.find('input[type="checkbox"]').is(':checked') ) {
        alert "found"
        //im getting data here.
        });
    }else{
        alert "NOthing found"
    };
});
like image 947
knowmeifyou Avatar asked Nov 14 '15 14:11

knowmeifyou


People also ask

How do I check if a checkbox is checked in a table?

change(function () { if ($("input[type='checkbox']:checked"). length > 0) $("#b1"). prop("disabled", false); else $("#b1"). prop("disabled", true); });

How do I automatically check a checkbox in HTML?

The checked attribute is a boolean attribute. When present, it specifies that an <input> element should be pre-selected (checked) when the page loads. The checked attribute can be used with <input type="checkbox"> and <input type="radio"> . The checked attribute can also be set after the page load, with a JavaScript.


1 Answers

No need to loop through anything. Just look for a checked checkbox inside dataTable with your selector. If it exists, then your "true" condition is met.

if ($('#dataTable input[type="checkbox"]:checked').size()) {
    // Proceed
}

Now, if you want to do something with the data inside the "checked" rows, you could do something like this:

var checkedItems = $('#dataTable input[type="checkbox"]:checked').each(function() {
    // Do something with the row
    console.log($(this).parent('tr').find('.data-selector').val());
});
if (!checkedItems.size()) {
    // Nothing was checked
}
like image 138
Steven Moseley Avatar answered Sep 25 '22 23:09

Steven Moseley