I have a table which looks a bit like this:
<table>
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td class='checkinput'>
<input type="checkbox" name="names" value="MD5_HASH"/>
</td>
<td>
John Doe
</td>
<td>
email@mail.com
</td>
</tr>
<!-- etc. -->
</tbody>
</table>
Essentially, I’m trying to build an application where you can select each row in the table that you want, then export the emails to a comma-delimited list. The problem I’m having is how to traverse the table and grab the information I need.
Currently, as a convenience, I’ve done the following to try and make it so that each row, when clicked, toggles the checkbox. Unfortunately, when clicking directly on the checkbox, nothing happens, as it tries to toggle itself as the JavaScript is called, returning it to where it was:
$("tr").click(function() {
var $checkbox = $(this).find(":checkbox");
$checkbox.attr('checked', !$checkbox.attr('checked'));
});
How can I optimize this to make it able to click the input itself and not have this conflict occur?
Also, when I’m finally ready to submit, how do I traverse the table and read the email from each row in which the <input> is selected?
[Edited to correct error in first part due to misunderstanding]
To prevent the undesirable checkbox behavior, exit your handler if the click was directly on the checkbox:
If the event originated from the checkbox, we let the checkbox perform its default behavior. Reference for learning.
To get the emails on just the checked rows, you should consider setting
class="email"on the<td>to make changes easier later on. Then, use something like this:Note also that you may want to trim that string to remove undesired whitespace at the beginning and end.
To learn about selectors used (
:checkbox,:checkedand:has) see here.