March 28, 2012

Checkbox confirm message – Remain checked if false

Question by benni_mac_b

I am currently trying to add a JavaScript confirm message when a user attempts to deselect an option.

If a user selects cancel on the confirm screen the check box should remain ticked. The problem I am having is that the check box becomes unchecked even if I return false.

Code example can be found here http://jsfiddle.net/Amjzv/

HTML

<div class="ServiceDesc Alternate">    
    <span class="expandable">
        <input id="ctl01_chk" type="checkbox" name="ctl01$chk" checked="checked">
    </span>                
</div>​

JQuery

$(document).ready(function () {
        //each load to persist state
        $('.expandable').each(function () {
            ToggleCheckboxes($(this),false);
        });
        $('.expandable').click(function () {
            ToggleCheckboxes($(this),true);
        });
    });
    //toggle child checkbox show/hide
    function ToggleCheckboxes(checkboxSpan, showConfirm) {
        if (checkboxSpan.find(':checked').length > 0) {
            checkboxSpan.parent().find('.indent').show();
        }
        else {
            if (showConfirm) {
                var answer = confirm("Are you sure?");
                if (answer) {
                    checkboxSpan.parent().find('.indent').hide();
                }
                else {
                    return false;
                }
            }
            else {checkboxSpan.parent().find('.indent').hide();}
        } 
    }​

Answer by iMoses

You are returning false inside your custom function, but not inside the function assigned to the click event. just fix the following line:

$('.expandable').click(function () {
    return ToggleCheckboxes($(this),true);
});

Answer by Starx

Simplest Way

$("#ctl01_chk").click(function() {
    if(confirm("Are you sure?")) { 
           // continue;
    } else { 
       return false;
    } 
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!