I want to have a confirmation from the user before they submit a form. This will prevent accidental POSTing of the form, that may be incomplete or incorrect.
Here is my form element:
<form action="manager.php?method=update&id=<?php echo $user->id;?>" onsubmit="return confirm_update();" method="POST" id="user_update">
This calls my function confirm_update()
function confirm_update()
{
if(confirm("Do you wish to update details?"))
{
return 0;
}
else
{
return 1;
}
}
The problem with the script is that it does not prevent the form from POSTing if the user clicks Cancel in the JavaScript prompt.
How do I correct this so that the user does not accidently submit their form?
Here is a full description of the feature I am trying to implement:
Use Case - "Update Details"
User goes to update page
User enters details in form fields
User hits submit button
Confirmation message appears
If "Ok" button selected proceed to submit form
Else cancel action and stay on current page
Instead of returning 0 and 1, return true and false. You can actually shorten the function to:
function confirm_update() {
return confirm("Are you sure you want to submit?");
}
You're doing it the other way round!
if(confirm("Do you wish to update details?"))
{
return 1;
}
else
{
return 0;
}
Having said that, your code can be shortened to just one line:
return confirm("Hit OK to continue, Cancel to... cancel.");
Try:
function confirm_update() {
if(confirm("Do you wish to update details?")) {
return true;
}
else {
return false;
}
}
I would do an onclick returning false by default, this works for me
<form action="manager.php?method=update&id=<?php echo $user->id;?>" method="POST" id="user_update">
<input type='submit' onclick="return confirm('Do you wish to update details?');return false;"/>
</form>
First of all you should reconsider your approach. Instead of asking whether the user wants to submit a potentially incomplete or invalid form, you should use javascript to prevent this from happening, i.e. perform client-side validation using js. What you are doing is inherently done by clicking submit...
If however you want to keep your approach, you have to prevent the submit button from actually submitting the data to the specified action, e.g by changing the form action to "#" via javascript and then trigger the submit if ok was clicked with your js-code, e.g. by using a XmlHttpRequest.
Related
I'm trying to use PureCSS forms in my web app and I can't figure out how to retain the nifty form validation while stopping the page reload.
I know I can stop the page reload using onsubmit="return false;"
Then I can use AJAX to post the form data using onClick="PostSettings();", where PostSettings() is my javascript function containing the AJAX request. I also have to include event.preventDefault(); at the top of that function to stop the reload.
Unfortunately these steps which stop the reload also stop the nice in-built PureCSS validation.
Is there a way to retain that without triggering the page reload or will I need to make my own validation in the javascript?
FYI, here's the html:
<button type="submit" class="pure-button pure-input-1-2 pure-button-primary"
id="save-simulation-button" onClick="PostSettings();"
onsubmit="return false;">
<i class="fa fa-save"></i> Submit Simulation Parameters
</button>
Use 'return false' instead of event.preventDefault() inside the 'PostSettings()' method.
Thanks for your replies Lucas and Vignesh -- they didn't quite solve the problem, but they got me thinking and I developed a solution:
In the html I had to add a return here: onClick="return PostSettings();"
Then in the javascript I return true or false depending on whether or not the form passes validation, which I have to check:
function PostSettings() {
//event.preventDefault(); <<- commented out per Vigneshs suggestion
var name = $("#simulation-name").val(); // jquery to get form values
var description = $("#description").val();
// Code to validate form: name and description cannot be blank
if (name === "" || description === "") {
console.log("name or description fields cannot be blank");
return true; // <<- returning true allows PureCSS validation to continue
}
// Code passed validation so post the data...
// POST code omitted for brevity
return false; // <<- returning false stops the page reload
}
So in summary, returning true allows the PureCSS form validation to take place as per normal (and there's no page reload because the form hasn't passed validation). And when the form passes validation I return false to stop the page reload -- this also stops any other default events of the PureCSS form, but that's okay because I manually checked if it validated in the javascript.
Hope this helps others who want to accomplish this in the future!
You only need a onsubmit="return MyValidFunction();" in the Form tag and nothing else in the "submit" button
When the form is not ok PureCSS make the validation with his message, When All is ok call your "MyValidFunction()" function
function MyFunction() {
/// your Ajax Code here
return false;
}
<form class="pure-form" onsubmit="return PostSettings();">
<input id="form_url" type="url" class="pure-input-1-3">
<button type="submit" class="pure-button pure-input-1-1">OK</button>
</form>
I had the same issue. Adding onsubmit="event.stopPropagation()" in the form tag prevents the refresh when the form is valid, and retains validation flags when it's invalid.
I've just wrote some validation code so as to check if either of my radio buttons from my web form have been selected before they are submitted. I've just starting learning php as I want to be able to store the value of each radio button in a .csv file.
Because I have my action attribute set to trigger a php script, I get my alert box, but as soon as I click OK after pressing submit the browser goes straight to the php script (inevitably).
Is there a way I can return to my initial index.html after the alert message?
I have not actually written any php as yet, so would this go in the php script or the javascript?
Heres my code so far:
$("#submit").on("click", function() {
var radio = $("input[type=radio][name=emotion]")[0].checked;
var radio2 = $("input[type=radio][name=emotion]")[1].checked;
var radio3 = $("input[type=radio][name=emotion]")[2].checked;
if(!radio && !radio2 && !radio3) {
alert("You must select at least one word!");
}
else {
alert("Please rate the next item!")
}
});
In Jquery you should use .submit() function to validate a form.
Then to avoid to submit the form you can use the function event.preventDefault()
And if you want to go to the index you can use window.location = "yourURL"
You must use form.onsubmit().
For example, if your form's name is myForm:
document.forms['myForm'].onsubmit = function()
{
if (this.elements['emotion'].value)
{
alert("Please rate the next item!");
}
else
{
alert("You must enter at least one word!");
return false;
}
}
And after alert "Please rate the next item!" form will be send.
Actually you can use jquery $.post() , an easy solution is just to post your php page without leaving index page.
http://api.jquery.com/jquery.post/
$.post( "yourpage.php" );
You probably have the input type of the submit button as submit? Set this to button, so the action doesn't take place and only jQuery is executed.
But then you have to submit the form by jQuery when validation was successful:
document.myFormId.submit();
This javascript works to confirm the form before it's submitted, however i don't know what to do to add a redirect link if they confirm true, or if they confirm false:
Javascript
<script>
function cancelalert(){
return confirm("By clicking OK you are submitting the form.");
}
</script>
HTML
onclick="return cancelalert()"
Instead of returning the result of confirm directly, put it in a variable and act accordingly:
var confirmed = confirm("By clicking OK you are submitting the form.");
if(confirmed)
{
return true; // will sumbit the form. Do a redirect on the server side
}
// not confirmed. Show an alert or something
There are lots of similar questions on here, but I haven't found any that deal with stopping a user from leaving a page after submitting a form (i.e. while it's processing).
I have a page on my website with a form that takes a long time to submit (sometimes as long as 15 seconds), so I want to have a popup warning to keep the user on the page after they submit the form.
The problem is that no matter how I try using window.onbeforeunload, I always get a confirmation dialog from that function when the form is submitted, which is not what I want. I don't want the user to get the confirmation dialog when the form is submitted, but rather after it's submitted and only if they try to leave the page after that.
HTML:
<form id="myform" method="post" action="" onsubmit="formSubmitted();">
<button type="submit" onclick="return checkForm();">submit form</button>
</form>
Javascript:
formSubmittedFlag = 0;
function checkForm()
{
...
if(...)
{
return true;
}
else
{
return false;
}
}
function formSubmitted()
{
formSubmittedFlag = 1;
}
window.onbeforeunload = function()
{
if(formSubmittedFlag == 1)
{
return "Are you sure you want to leave the page?";
}
}
Is there a way to accomplish what I'm wanting?
Submit the form using AJAX rather than the form's built-in action. The jQuery Form Plugin may be helpful.
replace the contents of formSubmitted with this:
sessionStorage.formSubmittedFlag=true;
notReloaded=true;
And replace the contents of window.onbeforeunload with this:
if(sessionStorage.formSubmittedFlag===true&¬Reloaded!=true)
return 'do you want to leave?';
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?
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();
}
}
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.
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.