简体   繁体   中英

How do I get the checkbox value from a specific cell in a table row using jQuery?

I have a table that contains multiple checkboxes in each row. I need to get the value of each individual checkbox. I've been able to do something like the following to retrieve the value of a checkbox in the first column of a table...

$('#myTable tbody tr td:first-child input:checkbox').each(function() {
        if (this.checked) {
            //Do something
        }
    });

But now I need to iterate over each row, and get the value of each individual checkbox. This is what I've been trying for a specific checkbox...

if($(this).find(':input[type="checkbox"]').eq(0).attr('checked')) {
            myVariable = 'so and so';
        }
        else {
            myVariable = 'something else';
        }

Which doesn't work. Any suggestions on how I can get this working?

Your question is not that clear however going from your second example I assume the 'this' is the tr. The below shows how to get the first checkbox inside the row and test if it is checked

if ( $(this).find('input:checkbox:first').is(':checked') ) {...}

To iterate all the checkboxes in the row

$(this).find('input:checkbox').each( function(){...}

To iterate all the checked checkboxes in the row

   $(this).find('input:checkbox:checked').each( function(){...}

Why not remove td:first-child from your selector?

$('#myTable tbody tr  input:checkbox').each(function() {
    if (this.checked) {
        //Do something
    }
});

Or if you want to group the checkboxes per row somehow:

$('#myTable tbody tr').each(function() {
    $(this).find('input:checkbox:checked').each(function() {
        //..
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM