Search code examples
javascriptjqueryhtmljquery-traversing

How to find specific elements with jQuery?


I have a table with checkboxes.

<tbody id="myTable">
<tr>
    <td>1</td>
    <td class="userName">Bob</td>
    <td><input id="u1" name="user" type="checkbox" value="1"></td>
</tr>
<tr>
    <td>6</td>
    <td class="userName">Izya</td>
    <td><input id="u6" name="user" type="checkbox" value="6"></td>
</tr>
</tbody>

How can I find all userNames of all checked inputs and put those names into the array?


Solution

  • Maybe use this dirty code:

    var tr = $('#myTable > tr'), un = $('#myTable .userName'), check = $('#myTable input[type="checkbox"]'), users = [];
    for (var i = 0; i < tr.length; i ++) {
        if (check[i].checked) {
            users.push(un[i].innerText);
        }
    }
    

    And then in array users, the users are there.