DDK
DDK

Reputation: 1038

How to get column data in a table row onchange of checkbox using jquery

I have a table which has checkbox column at the end.

HTML

<table border="1">
    <thead>
        <tr>
            <td>Name</td>
            <td>Amount</td>
            <td>Selected Rows</td>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Item 1</td>
            <td>5.0</td>
            <td><input type="checkbox" checked="checked"/></td>
        </tr>
        <tr>
            <td>Item 2</td>
            <td>3.0</td>
            <td><input type="checkbox" checked="checked"/></td>
        </tr>
        <tr>
            <td>Item 3</td>
            <td>4.0</td>
            <td><input type="checkbox" checked="checked"/></td>
        </tr>
    </tbody>
</table>
Total : $<input type="text" value="12.0" />

Jquery

$('input[type=checkbox]').change(function(){
   alert($(this).parent().parent().text());
});

I want to calculate the total value based on the rows selected using checkbox. The code $(this).parent().parent().text(); gives the text value of the entire row. How to get the value of amount column alone?

JSFIDDLE

Upvotes: 0

Views: 3786

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You need to loop through the rows and total up the checked values. Try this:

$('input[type=checkbox]').change(function () {
    var total = 0;
    $('table tbody tr').each(function () {
        if ($('input:checked', this).length) {
            total += parseFloat($(this).find('td:eq(1)').text());
        }
    });
    $('#total').val(total.toFixed(1));
});

Example fiddle

The DOM traversal could be improved to make it more specific to the table/inputs by adding some class or id attributes, but the pattern for calculating the total will work in any case.

Upvotes: 2

Related Questions