Jeremy
Jeremy

Reputation: 883

Retrieving values of checked checkboxes

I have a table (below) containing a value associated with a checkbox.

<table id="testTable">
<tbody>
    <tr id="tr1">
        <td><input type="checkbox" value="value1"></td>
        <td>row 1</td>
        <td>A</td>
    </tr>    
    <tr id="tr2">
        <td><input type="checkbox" value="value2" ></td>
        <td>row 2</td>
        <td>B</td>
    </tr>    
    <tr id="tr3">
        <td><input type="checkbox" value="value3"></td>
        <td>row 3</td>
        <td>C</td>  
    </tr>    
</tbody>

Once the user has selected any combination of checkboxes, I need to determine the values associated with any checkbox that has been checked (after the user clicks on a 'Finished' button).

This is what I have so far

$('#Finished').click(function() {

 $('#testTable tr').filter(':has(:checkbox:checked)').each(function() {

    $tr = $(this);
    $('td', $tr).each(function() {

        // NEED THIS BIT

    });

 });
});

I am having difficulty getting the values of the checkboxes that the user has selected.

Upvotes: 1

Views: 814

Answers (2)

Ionică Bizău
Ionică Bizău

Reputation: 113365

Just select selected checkboxes and collect the values:

var values = [];
$("input[type='checkbox']:checked").each(function () {
     values.push({"val": $(this).val(), "tr": $(this).closest("tr").attr("id")});
});

This will generate an array like this:

[
   {
       "val": "value1",
       "tr":  "tr1"
   },
   ...
]

...containing only checked checkboxes, sure.

JSFIDDLE

Upvotes: 2

Lee Meador
Lee Meador

Reputation: 12985

The easy way to tell which one is checked is to add an id to the <input> elements:

<tr id="tr1">
    <td><input id="cb1" type="checkbox" value="value1"></td>
    <td>row 1</td>
    <td>A</td>
</tr>  

Upvotes: 1

Related Questions