Domanda

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?

È stato utile?

Soluzione 2

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.

Altri suggerimenti

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

<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/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top