Function to mark/deselect checkbox, jquery

Asked

Viewed 8,986 times

6

How can I check/uncheck checkbox in jQuery by clicking a button and at the same time giving an Alert reporting whether it has been checked or unchecked..

2 answers

7


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 http://jsfiddle.net/ceLnm2eb/1/

  • helped me a lot, thanks for posting

6

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;        
            });         
        }
    });

});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.