Loop over html table and get checked checkboxes (JQuery)

后端 未结 3 1906
广开言路
广开言路 2020-12-31 02:03

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: <

相关标签:
3条回答
  • 2020-12-31 02:35
    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'));
             }
         });
    });
    

    Here is demo in JSFiddle.

    0 讨论(0)
  • 2020-12-31 02:44

    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!');
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-31 02:59

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

    $('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
     $('#out').append(this.id);
    });
    
    0 讨论(0)
提交回复
热议问题