Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check and uncheck inputs work only one time with Jquery

I am trying to check/uncheck all checkboxes by click on one checkbox in head of table. First click add attribute to inputs, second uncheck. It works only one time. Testing on Firefox and Chrome. Аttributes keep changing, but this is not shown in page. I see it only in browser debugger.

<table>
    <thead>
        <tr>
            <th><input type="checkbox" /></th>
            <th>#</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" /></td>
            <td>1</td>
        </tr>
        <tr>
            <td><input type="checkbox" /></td>
            <td>2</td>
        </tr>
        <tr>
            <td><input type="checkbox" /></td>
            <td>3</td>
        </tr>
    </tbody>
</table>

<script type="text/javascript">
$(function () {
    $('th input[type="checkbox"]').click(function(){
        if ( $(this).is(':checked') )
            $('td input[type="checkbox"]').attr('checked', 'checked');
        else
            // $('td input[type="checkbox"]').attr('checked', false);
            $('td input[type="checkbox"]').removeAttr('checked');
    })
});
</script>

Sample http://jsfiddle.net/aJhm9/

like image 980
glutaminefree Avatar asked Apr 16 '13 05:04

glutaminefree


People also ask

How do you uncheck a selected checkbox when one checkbox is unchecked?

Add another click event for checkbox under #checkboxlist , if a checkbox is unchecked then uncheck .

How can check multiple checkbox checked in jQuery?

Using jQuery, we first set an onclick event on the button after the document is loaded. In the onclick event, we created a function in which we first declared an array named arr. After that, we used a query selector to select all the selected checkboxes. Finally, we print all the vales in an alert box.


2 Answers

Use properties instead of attributes

$(function () {
    $('th input[type="checkbox"]').click(function(){
        if ( $(this).is(':checked') )
            $('td input[type="checkbox"]').prop('checked', true);
        else
            $('td input[type="checkbox"]').prop('checked', false);
    })
});

http://jsfiddle.net/aJhm9/2/

like image 145
Musa Avatar answered Nov 09 '22 04:11

Musa


.attr() is for modifying an elements default state only, not its live state Use .prop() for changing the live state of an element.

like image 24
Ken Herbert Avatar answered Nov 09 '22 03:11

Ken Herbert