JS form submission problem

Seeking advice on developing a functional contact form using HTML, CSS, and JavaScript. All conditions currently validate properly, but encountering an issue with error messages persisting after re-entering the required fields. Additionally, looking to redirect users to a new HTML page upon successful form submission. Any guidance or tips would be greatly appreciated. Embedding the code below for reference.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Register with us</title>

    <link rel="stylesheet" href="/css/bootstrap.min.css">

    <link rel="stylesheet" href="/css/styles.css">

</head>

<body style="position: relative;">

<div class="container"> <br>

        <h1 class="text-center">Register with Us!</h1>


        <form>
            <div class="form-group">
                <label for="fname" id="firstname">First name: </label>
                <input type="text" class="form-control" id="fname" placeholder="Enter your first name">
                <small id="firstnameerror" class="form-text"></small>
            </div>
            <div class="form-group">
                <label for="lname" id="lastname">Last name: </label>
                <input type="text" class="form-control" id="lname" placeholder="Enter your last name">
                <small id="lastnameerror" class="form-text"></small>
            </div>

            <div class="form-group">
                <label for="emailid" id="emailaddress">Email address:</label>
                <input type="email" class="form-control" id="emailid" aria-describedby="emailHelp"
                    placeholder="Enter email">
                <small id="emailerror" class="form-text"></small>
            </div>

...

#firstnameerror,
#lastnameerror,
#emailerror,
#passerror,
#phoneerror{
    color: tomato;
    font-size: 1.1em;
    margin-left: 10%;
    margin-top: 2.5%;
}

...

const form = document.querySelector(".container");
const firstname = document.getElementById("fname");
const lastname = document.getElementById("lname");
const emailid = document.getElementById("emailid");
const password = document.getElementById("pass1");
const confirmpassword = document.getElementById("confirmpass");
const phoneno = document.getElementById("phno");

// JavaScript function to handle form validation and error messages
function checkfname(fname) {
    // Validation logic for first name
    ...
}

...

Answer №1

To enhance the user experience, I recommend adding event listeners (on change) for each input field. Save the input values to variables and clear any error messages associated with that specific input. This approach is the most logical way to handle it.

For the submit function's redirection, you can follow one of the methods suggested by W3Schools:

// Simulate a mouse click:
window.location.href = "http://www.w3schools.com";

// Simulate an HTTP redirect:
window.location.replace("http://www.w3schools.com")

In addition, the following code snippet:

document.getElementById("firstnameerror").innerHTML.style = "none";

Will not achieve the intended result. You can either clear the text:

 document.getElementById("firstnameerror").innerHTML = "";

Or hide the element itself:

 document.getElementById("firstnameerror").style.display = "none";

Answer №2

.style = "none" may not achieve the desired result. Consider using

.style.display = "none"
instead.

In addition, many tasks you are attempting in JavaScript can also be accomplished through HTML form validation functions, such as the required attribute.

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

Alter the colors of all Divs inside a container with each click

Hey everyone, I'm just starting to learn JavaScript. I'm working on a project where I want to change the color of all the divs in a container every time they are clicked. For example, on the first click, I want all the divs to turn red. Then, on ...

Organize information in a React table following a predetermined sequence, not based on alphabetical order

As a beginner with React, I'm looking to sort my data by the column "Status" in a specific order (B, A, C) and vice versa, not alphabetically. The data structure looks like this: export interface Delivery { id: number; name: string; amount: num ...

Ways to prevent images from vanishing when the mouse is swiftly glided over them

Within the code snippet, the icons are represented as images that tend to disappear when the mouse is swiftly moved over them. This issue arises due to the inclusion of a transition property that reduces the brightness of the image on hover. However, when ...

Designing a personalized carousel component in Angular

Looking to replicate this design, any tips? I'm aiming for a carousel layout with developers listed in a project, where the center item is larger than the others. Any guidance on how to achieve this look? ...

Need Root Directories in Browserify and Using NPM (eliminating the constant use of '../../../..' in both cases)

Despite my extensive search for a solution to this issue, I have been unsuccessful so far – even after referring to the amazing gist on improving local require paths and thoroughly reading the Browserify handbook section on Avoiding ../../../../... I am ...

Ways to incorporate a dictionary into your website's content

I am in the process of developing a website for educational purposes while also honing my web programming skills. On this website, I have encountered some complicated terms that may be difficult for users to understand, so I want to implement a tooltip/mod ...

Exploring Angular 2 with ng-bootstrap Library

As I delve into learning Angular2, my goal is to incorporate ng-bootstrap into my project. However, I have encountered issues when trying to import ng-bootstrap and create a functional project. Being a novice in this field, I am unsure if the problem lies ...

I seem to be encountering an issue while looping through an array of objects. Instead of retrieving all two elements, only one object is being returned. Can

Just a heads up, I'm new to coding so please bear with me. I'm attempting to run through the "diary" array and the function "howMany" is only showing 2 'Home' elements, although there are actually 4 'Home' elements in total i ...

I'm unsure about the JavaScript toolkit framework's handling of selecting HTML class attributes

I have been exploring the Electron Framework using a JavaScript toolkit known as Xel. In my main.js file, I am working with the following syntax: document.querySelector("menu.selected").className.remove('selected') In my Xel code snippet, I hav ...

Upon selecting multiple checkboxes, corresponding form fields will be displayed based on shared attributes

When multiple checkboxes are selected by the user, corresponding form fields should appear based on the checkboxes. For example, if both flight and hotel checkboxes are checked, then the full name and last name fields should be displayed while other fields ...

The vertical-align property in CSS seems to be malfunctioning

Hi there, I'm struggling with the CSS code below: .parent { position : 'absolute'; top : '50px'; left : '50px'; width : '400px'; height : '160px'; padding : '10px'; ...

Connecting Documents and Organizing Folders

Currently, I am immersed in a web project leveraging java/ jsp/ servlets/ html/ css within Eclipse Tomcat. At the core of this project, all files are nestled neatly within the WebContent folder. Within my jsp files, I have encountered an issue when trying ...

What is the best way to declare a variable in order to apply a custom background color to a

I am having trouble getting the conditional background color to apply to the textbox when I set the variable columnstyle. Here is the snippet of HTML code: var columnstyle = "text-align:center;vertical-align:central;background-color:#FFBF00"; ...

My keyframes seem to be malfunctioning, despite exhausting all my troubleshooting options

Could someone please help me figure out why the @keyframes rule is not working for me? I've tried adding -webkit- as a fix, but it doesn't seem to be helping at all. .keyframe { height: 15px; width: 50px; background-color: red; -webkit ...

What is the code in CodeIgniter to retrieve the string 'Sugar & Jaggery, Salt' using <a>?

Can someone please help me? I am a beginner in CodeIgniter and I am having trouble passing a URL with a string. The controller is not accepting the string as expected. How can I fix this issue? //Below is the HTML code for passing a string value index.ph ...

Could you explain the concept of implodeQuery to me?

While browsing through the source page of Facebook, I came across a function that is commonly used. The specific line of code was: input_len=URI.implodeQuery(this.data).length I am having trouble understanding what this line of code means and what exactl ...

Can Chrome support color management for css colors?

In my current project, we are dealing with designers who work in Adobe RGB and are accustomed to viewing the vibrant colors from that spectrum in Illustrator. However, we are developing an application that will enable them to work in a web browser using a ...

Tips for assigning dynamic #id(*ngFor) and retrieving its value in Angular2

In my HTML file, I have the following code snippet: <tr *ngFor="let package of packages"> <td *ngFor="let coverage of coverages"> <input type="hidden" #dynamicID [value]="coverage.id"> <-- Include an identifier with the vari ...

Ensure that the HTML input only accepts numbers and email addresses

Is there a way to restrict an HTML input field to only accept numbers and email IDs? <input id="input" type="text" /> ...

Styling for the bootstrap dropdown menu is missing

While attempting to incorporate a bootstrap dropdown menu, I noticed that despite applying the appropriate class to the sublist, the formatting and padding that is typically associated with bootstrap are not being retained. My current setup involves using ...