0
votes


I've got a form with a number of fields and a few checkboxes. When the user clicks save, if a certain checkbox isn't checked, they're prompted with a 'Confirm' dialog box asking if they still want to save the form. If they click okay, the button should fire it's event handler normally, but if they click cancel, nothing should happen.

function checkVerification(checkBox)
{
    if (!document.getElementById(checkBox).checked)
    {
        confirm('Worksheet has not been verified. Save anyway?');            
    }
}

As of right now, the Save button's event handler fires regardless of the user's choice. Any advice would be greatly appreciated.

5

5 Answers

2
votes

Just return false if the user declines to save, like this:

return confirm('Worksheet has not been verified. Save anyway?');

confirm() will return true if the user clicked 'Yes' and false if they clicked 'No.' Returning false instructs the browser to stop processing the event normally.

2
votes
var ok = confirm('Worksheet has not been verified. Save anyway?');
if (ok) {
    // trigger
}
1
votes

You need to tie the return value of the confirm dialog to the OnClientClick of the button, like this:

<asp:Button ID="Button1" runat="server" OnClientClick="return confirm('Are you sure?');" ... />

In this case, if user clicks Yes the page will perform a postback. If the user clicks No the postback will be aborted.

After looking at your comment, try this:

btnSave.OnClientClick = String.Format("return checkVerify('{0}');", cbVerified.ClientID);

And in your JavaScript function:

function checkVerify(checkBox)
{ 
    bool continue = true;
    if(!document.getElementById(checkBox).checked) {
        continue = confirm('Worksheet not verified. Would you like to save?');
    } 
    return continue;
}
0
votes

Assuming the verification is bound to the onsubmit event you can just return false from the handler and the form won't be submitted.

Also, if you are using jQuery, the method event.preventDefault() would do the same.

0
votes

Without seeing more of your code it's hard to tell exactly, BUT one problem could be your if statement. To ensure proper type checking use === instead of assuming your value is a boolean.

if(document.getElementById(checkBox).checked === false) { ... }

You could also have more than one checkbox on the page with the same id value...if one is checked and one isn't document.getElementById might be getting the one that isn't checked.

Hope that helps.