Guide on redirecting a webpage post form validation in JavaScript

I have a question about my JavaScript code. Even if validation fails, the contact us page still appears. How can I fix this issue? Appreciate any help. Thank you!

(function () {
    window.addEventListener('load', function () {
    var forms = document.getElementsByClassName('needs-validation');
    var validation = Array.prototype.filter.call(forms, function (form) {
    form.addEventListener('submit', function (event) {
    if (form.checkValidity() === false) {
    form.classList.add('was-validated');
    event.preventDefault();
    event.stopPropagation();
    }
                                                                    
    form.classList.add('was-validated');
    window.location.href = "contact.html";
    
    
    
    }, false);
                                                                    
    });
    }, false);
    })();

Answer №1

When reviewing your code, I noticed that you are checking the form validation result, which is good practice. However, at the end of the code, you are still redirecting the user. To address this issue, consider adding a `return;` statement in your code after validation fails or placing the redirection within an else block.

(function () {
window.addEventListener('load', function () {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
form.classList.add('was-validated');
event.preventDefault();
event.stopPropagation();
return;
}
                                                                
form.classList.add('was-validated');
window.location.href = "contact.html";


}, false);
                                                                
});
}, false);
})();

Alternatively:

(function () {
window.addEventListener('load', function () {
var forms = document.getElementsByClassName('needs-validation');
var validation = Array.prototype.filter.call(forms, function (form) {
form.addEventListener('submit', function (event) {
if (form.checkValidity() === false) {
form.classList.add('was-validated');
event.preventDefault();
event.stopPropagation();
} else {
form.classList.add('was-validated');
window.location.href = "contact.html";
}


}, false);
                                                                
});
}, false);
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I'm having trouble seeing my remarks in the comment section

I've been working on setting up a comment section for my website, and I'm facing an issue with displaying the comments that users post in the database on the front end. When I try to retrieve and display the comment using a function, it doesn&apo ...

How can you determine if multiple checkboxes have been checked with "if" statements following a button click?

I am looking to display a message after clicking a button if one or more checkboxes are checked. I would prefer using Jquery for this functionality. Any help on achieving this would be highly appreciated. $(function() { $(".btn").click(function() { ...

How can scripts be used to enable fullscreen in PhoneGap?

Can JavaScript in PhoneGap enable fullscreen mode and hide the status bar? While I know it can be pre-defined in config.xml, I'm unsure if it can be changed dynamically. I've come across resources suggesting that plug-ins are necessary here, but ...

How to eliminate undefined values from a dropdown selection in AngularJS

Blockquote When choosing a material from the column, the first option is showing as undefined. How can I remove undefined from the drop-down list? What changes need to be made in the HTML/JSON data for this to work properly? Blockquote var app = ang ...

Finding the perfect spot to CAPTURE an ERROR triggered during an EVAL operation

This snippet of code allows you to run JavaScript code while using a try/catch block to catch any errors that may occur. try { var result = eval(script); } catch (e) { // handle the error appropriately } However, if the variab ...

Approval still pending, awaiting response

Encountering an issue with a POST request using React and Express, where the request gets stuck in the middleware. I am utilizing CRA for the front end and Express JS for the backend. Seeking advice on troubleshooting this problem. Backend server.js var ...

The issue arises when d3.scaleLinear returns NaN upon the second invocation

My journey with d3.js is just beginning and I'm taking it slow. Currently, I'm focused on creating a bar chart where data is loaded from a json file. When I click on the bars, the data changes to another column in the json. This is how my json f ...

Executing a REST call only when the previous one has successfully completed

Is there a way to execute a second REST request only after multiple successful responses from the first one? I have noticed that while in a normal state these requests are executed sequentially as required, issues arise when dealing with a large number o ...

What is the best way to create a navigation bar that opens on the same page when clicked?

Can someone help me figure out how to create a navbar that, when clicked, opens a small window on the same page like in this example image? ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

Switching Over to Burger Menu

I created a burger menu using HTML, CSS, and jQuery that switches from a full-width menu to a burger menu. However, I'm facing an issue with toggling the dropdown when the menu collapses. Here's my code: <!DOCTYPE html> <html> < ...

Transforming a redux form onSubmit function into a promise-based structure

One of my goals is to promisify the onSubmit handling in my submitForm for redux form. You can find a similar example here. submitForm = () => { return this.props.submituserForm() .then(() => { console.log('test') }) ...

Ways to identify if the text entered in a text area is right-to-left justified

Within a textarea, users can input text in English (or any other left-to-right language) or in a right-to-left language. If the user types in a right-to-left language, they must press Right-shift + ctrl to align the text to the right. However, on modern O ...

Delete the designated column from the table

I am having difficulty with hiding and showing table columns using checkboxes. I need to eliminate the Mars column (in bold) along with its corresponding data (also in bold). Once the Mars column is removed, I want the Venus column and its data values to ...

Sending a document to a distant server using a background script in Thunderbird

I am currently working on a Thunderbird extension that has the ability to upload attached files in emails. The process flow of this extension is outlined below: Clicking on the extension icon will display a popup with options to select from: "Read All", " ...

JSON Array Position Sequence

I have a system that takes input in the form of lines of text stored as an array, for example: array[123,556,"test",0,0]. By using val().split('\n'), I am able to add each new line to the array so that each line index is incremented by 1. He ...

Explaining the implementation of JQuery's onload event and its impact on reducing dependencies

Contained within a table is some data https://i.stack.imgur.com/gQyJQ.png Upon clicking the edit button, I am able to modify the information in that specific row. The Menu Category and Menu are populated through Dependent dropdowns. https://i.stack.imgur ...

Adding variables and appending using jQuery

When using the append method to add HTML content dynamically to a div, I encountered an issue while trying to insert an iframe. Specifically, I needed to pass a variable's value to this frame for it to function properly. Here is the code snippet: va ...

Unable to provide feedback on the input elements

ISSUE: Unable to provide input in the input fields // Enable dragging for the DIV element: dragElement(document.getElementById("mydiv")); function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (document.getElementB ...

differences in opinion between JavaScript code and browser add-ons/extensions

As the owner and developer of an e-commerce website, I find that potential customers often contact us regarding ordering issues. Upon investigation, we consistently discover that the problem is caused by JavaScript errors. We frequently check their browse ...