Function to mark / uncheck checkbox, jquery

5

How can I check / uncheck checkbox in jQuery when I click on a button and at the same time give an alert whether it has been checked or unchecked.

    
asked by anonymous 06.02.2015 / 05:25

2 answers

6

In this way:

$('#btn').click(function(){

    if($( '#mycheckbox' ).prop( "checked" ) == true){
           alert('desmarcado')
           $( '#mycheckbox' ).prop( "checked" , false)
    } else {
         alert('marcado')
         $( '#mycheckbox' ).prop( "checked" , true)
    }
})

See the example working on here link

    
06.02.2015 / 05:49
5

HTML:

<ul class="chk-container">
    <li><input type="checkbox" id="selecctall"/> Selecionar todos</li>
    <li><input class="checkbox1" type="checkbox" name="check[]" value="item1">Item #01</li>
    <li><input class="checkbox1" type="checkbox" name="check[]" value="item2">Item #02</li>
    <li><input class="checkbox1" type="checkbox" name="check[]" value="item3">Item #03</li>
</ul>

JS:

$(document).ready(function() {
    $('#selecctall').click(function(event) {
        if(this.checked) {
            $('.checkbox1').each(function() {
                this.checked = true;               
            });
        }else{
            $('.checkbox1').each(function() {
                this.checked = false;        
            });         
        }
    });

});
    
06.02.2015 / 05:47