简体   繁体   中英

Get column in a row in a table if that row has a selected checkbox

I have a table like the following

<table id="adminTable">
<thead>
<tr>
<th></th>
<th>Username</th>
<th>Email</th>
<tr>
</thead>
<tbody>
<tr><td><input type='checkbox' name='selected_users[]' value='User1'/></td><td>User1</td><td>mail1@mail.com</td></tr>
<tr><td><input type='checkbox' name='selected_users[]' value='User2'/></td><td>User2</td><td>mail2@mail.com</td></tr>
...
</tbody>
</table>

I have a button below which calls a javascript-function. This function then should get all the emails for the users which were selected via their checkboxes...

I am quite new to Javascript and jQuery an am not sure of how to achieve this... But I can use plain Javascript or use jQuery...

What I already found was this , but I can't get it to help me, because I don't want a button in my row (multiple selections shall be possible via the checkboxes).

You can use the following function which run on a button click:

$(":button").click(function() {
    var emails = $("input[name=selected_users[]]:checked").map(function() {
        return $(this).closest("td").next("td").text();
    }).get();

    console.log(emails); //array of emails that were checked
});
$("#adminTable").find("td").filter(function() 
{ 
    return $(this).find("input[type=checkbox]:checked").length > 0;
}); 

Keep in mind you have TR tags in your html that don't have closing tags and are out of place.

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