views:

457

answers:

3

I'm having a problem with submitting a form and Javascript confirmation. Basically, the following Javascript is called when the "submit" button is pressed.

function confirmation() {
    var answer = confirm("Are you sure you wish to edit?")
    if (answer)
    {
     window.location = "#editform2";
    }
}

However, when I hit the cancel instead of ok, the Javascript executes correctly, because I watch the address bar and it doesn't update to #editform2. The form, however, still submits. It seems to refresh the page. Here's the relevant parts from the form:

//Form is encoded in PHP
<form method=\"post\">
//Form is in here
<input type=\"submit\" value=\"Edit\" onclick=\"confirmation()\">

So the form doesn't know where it's going, it just refreshes the page, and the page happens to be the processor as well. So it's processing even though I clicked cancel and the Javascript should keep it on the same page. Besides moving the processing to a different page, what are my solutions?

+1  A: 

try:

return answer;

at the end of the function and make sure the onclick method returns this. Like so:

<input type="submit" value="Edit" onclick="return confirmation()">

This would make the function return false and have the form not be posted.

Robban
+3  A: 

It works like this because it's a sumbit button and the form is submitted in every case. Assign an id to the form and change the input type:

<form method="post" id="formid">
<input type="button" value="Edit" onclick="confirmation()">

and call this function on click:

function confirmation() {
    var answer = confirm("Are you sure you wish to edit?")
    if (answer)
    {
        document.getElementById("formid").submit();
    }
}
mck89
A form is not submitted in every case, if the method returns false the form will not be submitted...
Robban
+2  A: 

Don't use the onclick event of the submit button, use the onsubmit event of your form:

document.forms[0].onsubmit = function () {
    return confirm("Are you sure you wish to edit?");
}

You may want to add a id attribute to your form to identify it.

Keeping event binding on JavaScript code; not on inline attributes on your HTML, makes your code more maintanable and easy to debug.

CMS
+1, but `document.forms[0]` is not a great maintainability solution. Giving the form a name or id would be better.
nickf
Agree, thanks, was only for example purposes, that's why I suggest adding an id...
CMS