Home > Web Front-end > JS Tutorial > How Can I Reliably Stop JavaScript Form Submission and Navigate Back?

How Can I Reliably Stop JavaScript Form Submission and Navigate Back?

Susan Sarandon
Release: 2024-12-23 12:50:22
Original
1021 people have browsed it

How Can I Reliably Stop JavaScript Form Submission and Navigate Back?

Stopping Form Submission with JavaScript

Form submission can be prevented in JavaScript using various methods. One method mentioned in the question is to return false from the validation function when specific conditions are met. However, in this case, the form is submitting even after calling the returnToPreviousPage() function.

To effectively stop form submission and return to the previous page, consider the following approaches:

1. PreventDefault() and Return False:

Add the preventDefault() method to the form's onsubmit event handler and return false from the validation function. This will prevent the browser from submitting the form and will trigger the returnToPreviousPage() function to navigate back to the previous page:

<form onsubmit="event.preventDefault(); validateMyForm();">
Copy after login
function validateMyForm() {
  if (condition not met) {
    alert("Validation failed");
    returnToPreviousPage();
    return false;
  } else {
    alert("Validation passed");
    return true;
  }
}
Copy after login
Copy after login

2. Return Value of Function:

Use the return value of the validation function to control form submission. In the onsubmit event handler, specify the name of the validation function and set the return value of the function to stop or allow submission:

<form onsubmit="return validateMyForm();">
Copy after login
function validateMyForm() {
  if (condition not met) {
    alert("Validation failed");
    returnToPreviousPage();
    return false;
  } else {
    alert("Validation passed");
    return true;
  }
}
Copy after login
Copy after login

Note: If using Chrome 27.0.1453.116 m, it may be necessary to set the returnValue field of the event parameter to false for the above code to work effectively.

The above is the detailed content of How Can I Reliably Stop JavaScript Form Submission and Navigate Back?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template