christiangobo
christiangobo

Reputation: 530

jQuery foreach checkbox checked in tr > first td

i want to iterate through the table rows and get the id and name of each checkbox checked in each tr in the first td and save it in a new Object() called values ex: values.id, values.name

Thanks

<table>
    <tr>
        <td>
            <input id="1" type="checkbox" name="name1" checked="checked">
        </td>
        <td>
            Some input control 1
        </td>
    </tr>
    <tr>
        <td>
            <input id="2" type="checkbox" name="name2">
        </td>
        <td>
            Some input control 2
        </td>
    </tr>
</table>

Upvotes: 0

Views: 7433

Answers (2)

Tracy Fu
Tracy Fu

Reputation: 1662

http://jsfiddle.net/tracyfu/r6RMV/

var values = {};

$('tr input:checked').each(function(i) {
  values[i] = [];
  values[i].push($(this).attr('id'));
  values[i].push($(this).attr('name'));
});

Will produce:

values = { [1, 'name1'] }

I'm leaving this solution as-is, since you specifically said you wanted to store the values in an object named values, but without knowing what you're going to do with the data, I would store the values in an array instead...

Upvotes: 0

Elliot B.
Elliot B.

Reputation: 17681

Working example

aRecord is an array of objects with each object containing both the name and ID of each checked checkbox found in the table.

$(document).ready(function() {
   var aRecord = [];
    $('#your_table input:checkbox:checked').each(function() {
        var oChkBox = {};
        oChkBox.name = $(this).attr('name');
        oChkBox.id = $(this).attr('id');
        aRecord.push(oChkBox);
    });

    var i = aRecord.length;
    while (i--) {
        alert("Name: "+ aRecord[i].name   + " ID: "+ aRecord[i].id);
    }

});

Upvotes: 3

Related Questions