Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select all checkbox only works twice

I got this code from stackoverflow which looks like a pretty good "select all" checkbox solution, any ideas why it fails after 2nd click?

http://jsfiddle.net/R9zjk/2/

<table>
    <tr>
        <td>
            <input type='checkbox' value='0' class=''>
        </td>
        <td>
            <input type='checkbox' value='0' class=''>
        </td>
        <td>
            <input type='checkbox' value='0' class=''>
        </td>
        <td width="100" align="right">
            select all <input type='checkbox' value='0' class='selectall2'>
        </td>
    </tr>
</table>

$(document).ready(function () {


    $(document).on("click", ".selectall2", function () {


        $(this).closest('tr').find('input[type=checkbox]').attr('checked', this.checked);


    });



});
like image 813
jim smith Avatar asked Dec 01 '22 20:12

jim smith


1 Answers

use .prop() instead of .attr() above jQuery 1.6

If using jQuery 1.6, the code if ( $(elem).attr("checked") ) will retrieve the actual content attribute, which does not change as the checkbox is checked and unchecked. It is meant only to store the default or initial value of the checked property. To maintain backwards compatability, the .attr() method in jQuery 1.6.1+ will retrieve and update the property for you so no code for boolean attributes is required to be changed to .prop(). Nevertheless, the preferred way to retrieve a checked value is with one of the options listed above. To see how this works in the latest jQuery, check/uncheck the checkbox in the example below.

See .prop()

demo - http://jsfiddle.net/f9QYx/

like image 128
pktangyue Avatar answered Dec 15 '22 09:12

pktangyue