0

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?

Finkelson
  • 2,921
  • 4
  • 31
  • 49
  • 1
    Are you using the same `id` multiple times? The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document). if it is unique, try `document.getElementById("userName").innerHTML` – James King Apr 20 '14 at 14:40

3 Answers3

2

Try

var usernames = $('#myTable')
    .find('tr:has(input.user:checked)')
    .find('.userName').map(function(){
        return $(this).text();
    }).get();

It will create an array with all usernames, whose relevant check box is checked

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
1

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.

xhg
  • 1,850
  • 2
  • 21
  • 35
0
<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>

You should use class instead of id, because an id should be unique to the page.

Using jQuery:

$('input[type="checkbox"]').prop('checked').siblings('.userName').text();

Or if you need the name attribute of the input:

$('input[type="checkbox"]').prop('checked').attr('name');

http://api.jquery.com/category/selectors/

Joel
  • 665
  • 2
  • 9
  • 23