Professor Chaos Professor Chaos - 9 days ago 5
jQuery Question

jQuery checkbox change and click event

I have

<input type="checkbox" id="checkbox1" /> <br />
<input type="text" id="textbox1" />


and

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

$('#checkbox1').change(function() {
$('#textbox1').val($(this).is(':checked'));
});

$('#checkbox1').click(function() {
if (!$(this).is(':checked')) {
return confirm("Are you sure?");
}
});
});


JSFIDDLE link

Here the changed event updates the textbox value with the checkbox status. I use the click event to confirm the action on uncheck. If the user selects cancel, the check mark is restored but the change even fires before confirmation leaving things in a inconsistent state (the textbox says false when the checkbox is checked). How can I deal with the cancellation and keep textbox value consistent with the check state?

Thanks

Answer

Well I don't see an answer that matches mine so I'll post this. Tested in JSFiddle and does what you're asking for.This approach has the added benefit of firing when a label associated with a checkbox is clicked.

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

    $('#checkbox1').change(function() {
        if($(this).is(":checked")) {
            var returnVal = confirm("Are you sure?");
            $(this).attr("checked", returnVal);
        }
        $('#textbox1').val($(this).is(':checked'));        
    });
});