Checkbox Tick Event

by vikrant singh

HTML

<input type="checkbox" id="myCheckBox" />
<br />
<input type="text" id="textbox1" />
<button onclick="toggleCheckBox()">Toggle Checkbox</button>

JavaScript

function toggleCheckBox() {
    var $myCheckBox=$('#myCheckBox');//better store ref into local variable
    if ($myCheckBox.is(":checked")) {
        $myCheckBox.prop('checked', false)
    } else {
        $myCheckBox.prop('checked', true);
    }
    $myCheckBox.change();//trigger change 
}

$(document).ready(function () {
    //set initial state.
    $('#textbox1').val($(this).is(':checked'));

    //This Event is not called when toggled by button
    $('#myCheckBox').change(function () { //-------------if(this.checked
        if ($(this).is(":checked")) {
            var returnVal = confirm("Are you sure?");
            $(this).attr("checked", returnVal);
        }
        $('#textbox1').val($(this).is(':checked'));
    });
});