Reputation: 245
So I have a form that when submitted requires confirmation. I am using Javascript confirm to prompt for this. However, I do not want it to refresh if someone hits cancel. I thought putting an empty else statement would do so, however it appears I was wrong.
Not sure what I need to be doing to make sure it does NOT refresh if someone presses cancel on the popup.
function postConfirm() {
if (confirm('You will not have another chance after submitting to view your post. Please make sure it is exactly how you want it before continuing. ')) {
yourformelement.submit();
} else {
}
}
<div id="uploadForm">
<center>
<form enctype="multipart/form-data" action="functions/post_upload.php" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="99999999" />
<div><textarea id="text" cols="70" rows="15" name="entry"></textarea></div>
<p> Attach an image to this memory!</p>
<input name="userfile" type="file"><br>
<input type="submit" value="Submit" class="blueButton" onclick="postConfirm()"/></div>
</form></center>
</div>
Upvotes: 3
Views: 7722
Reputation: 43166
You can prevent form submission using the preventDefault()
method of event object and manually submit the form upon confirmation using the submit()
method of form elements.
Change your HTML
to:
<input type="submit" value="Submit" class="blueButton" onclick="postConfirm(event)"/></div>
function postConfirm(e) {
e.preventDefault();
if(confirm('You will not have another chance after submitting to view your post. Please make sure it is exactly how you want it before continuing. '))
yourformelement.submit();
}
However, it is better to avoid inline javascript since it is considered a bad practice. Instead you can do:
var button = document.getElementsByClassName("blueButton")[0];
button.addEventListener("click",function(e) {
e.preventDefault();
if(confirm('You will not have another chance after submitting to view your post. Please make sure it is exactly how you want it before continuing. '))
yourformelement.submit();
});
Upvotes: 0
Reputation: 329
try adding
return false;
to the else part of your if statement.
Edit:
Also modify your call to the function so that the return false is passed back to the submit action (which is fired when the button is clicked).
<input type="submit" value="Submit" class="blueButton" onclick="return postConfirm()"/></div>
Upvotes: 3
Reputation: 992
try
<input type="button" value="Submit" class="blueButton" onclick="postConfirm()"/></div>
instead of
<input type="submit" value="Submit" class="blueButton" onclick="postConfirm()"/></div>
Upvotes: -2
Reputation: 208032
Change:
onclick="postConfirm()"
to
onclick="return postConfirm()"
and in your function, make the else:
else {
return false;
}
Upvotes: 11