Posts Tagged ‘checkbox’

Overriding checkbox behaviour adding a confirm popup

Tuesday, December 16th, 2008

I recently needed to add a confirm dialog for an asp checkbox. The confirm popup should determine whether the checkbox is posted back to the server or returned to its original state. Merely adding a onclick=”return confirm(’blah blah’)” here will not work because the post back will never occur (see why below). Because of this I whipped up this quick easy hack that I will share with you.

I defined a typical checkbox that auto post backs when its change event occurs:


<asp:CheckBox AutoPostBack="true" Text="Status" ID="chkExample" runat="server" OnCheckedChanged="OnCheckedChangeLabel" />

The markup that is generated for us by asp then looks like this:

<input id="chkExample" type="checkbox" name="chkExample" checked="checked" onclick="javascript:setTimeout('__doPostBack(\'chkExample\',\'\')', 0)" />

So essentially what we want to do is bypass this __doPostBack call so that we can post back only when our confirm popup returns true, so lets write a javascript function to do just that…

    <script type="text/javascript">

        function OverrideCheckPostback() {
            if (confirm("Are you sure?")) {
                __doPostBack('chkExample', '');
                return true;
            }
            else
                return false;
        }
    </script>

And then in our PageLoad we add the onclick attribute and specify the our function to be called.

    protected void Page_Load(object sender, EventArgs e)
    {
        chkExample.Attributes.Add("onclick", "return OverrideCheckPostback();");
    }

Now lets look at the code that gets generated for us. As we can see the original generated post back call is still there, but will never be called because we return before it has a chance while returning the value of our confirm popup. The post back is now handled in our own function only when confirm() returns true (aka the user presses ‘OK’).


<input id="chkExample" type="checkbox" name="chkExample" onclick="return OverrideCheckPostback();setTimeout('__doPostBack(\'chkExample\',\'\')', 0)" />