JeffVader JeffVader - 5 months ago 9
jQuery Question

jQuery: multiple checkboxes, get the value of the only checked one

I've got a script that shows a value when one checkbox is checked and doesn't show any value when more than one checkbox is checked.

This is working to a point.
If I select one checkbox I get the value associated to it's nearest

class=list
, if I click a second checkbox I get nothing and that is correct.

However when I unselect the second checkbox the alert shows it's value not the value of the last remaining checked check box.

So how do I get the value of the only checked checkbox ?

This is the layout of the checkbox and it's nearest
class list


<tr>
<td>1</td><td><input type='checkbox' name='id[0]' id='0'/></td>
<td class='list'><span>1234</span></td>
<td><span></span></td>
</tr>


This is the jQuery I'm using :

$(document).ready(function () {
var count;
$(':checkbox').change(function() {
count = ( $('input[type="checkbox"]:checked').length ) ;
txt = $(this).closest('tr').find('.list').text();
if (count == "1" ) {
alert (txt)
}
});
});


Here is a JSFiddle showing the issue : http://jsfiddle.net/f7qcuwkf/
If you check option 1 the alert shows 1234.

If you check option 3 then nothing shows (this is correct) If you uncheck either option you see it's value and not the value of the remaining checked entry. EG::

Uncheck 3 I get 3456, NOT 1234 ( 1 is still checked )

Any ideas how to resolve this ?

Thanks

Answer

If you traverse the DOM with this, you'll get the vaue of the changed checkbox. You need to traverse the DOM with the checked box. To do that, you can cache the selected checkboxes and traverse the DOM with it.

$(document).ready(function () {
    var count;
    $(':checkbox').change(function() {
        var $checkboxes = $('input[type="checkbox"]:checked');
        count = ( $checkboxes.length ) ;

        if (count == "1" ) {
            var txt = $checkboxes.closest('tr').find('.list').text();
            alert (txt)
        } 
    });
});  

http://jsfiddle.net/f7qcuwkf/5/

Comments