JeffVader
JeffVader

Reputation: 702

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

Upvotes: 1

Views: 3571

Answers (3)

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

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/

Upvotes: 1

Lenon Bordini
Lenon Bordini

Reputation: 39

When you change, you are catching the text from the checkbox triggered, and not from the checkbox checked.

$(":checkbox:checked").closest("tr").find('.list').text()

http://jsfiddle.net/f7qcuwkf/1/

Upvotes: 0

n-dru
n-dru

Reputation: 9430

You need to assign txt variable this way (look for the closest row to the checked checkbox, and not to the one that was changed):

txt = $('input[type="checkbox"]:checked').closest('tr').find('.list').text();

Demo

Upvotes: 0

Related Questions