lundi 21 mars 2016

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 jqeury 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://ift.tt/1XHmwtw 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




Aucun commentaire:

Enregistrer un commentaire