I'm seeking assistance in identifying the issue with my form validation code. Could anyone lend a hand?

<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="./css/createanaccount.css">
        <script src="https://kit.fontawesome.com/c90e5c3147.js" crossorigin="anonymous"></script>
    </head>
    <body>
        <div class="container">
            <div class="header">
                <h2>Create An Account</h2>
            </div>
            <form class="form" id="form">
                 ... (Your content goes here) ...
            </form>
        </div>

        <script src="js/createanaccount.js"></script>
    </body>
</html>

@import url('https://fonts.googleapis.com/css2?family=Poppins&display=swap');

*{
    box-sizing: border-box;
}

body{
    background-color: #9b59b6;
    font-family: "Poppins", sans-serif;
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 100vh;
    margin: 0;
}

span{
    font-size: 0.8rem;
}
.container{
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
    overflow: hidden;
    width: 400px;
    max-width: 100%;
}
... (Remaining CSS styles go here) ...

// JavaScript code goes here

I am currently working on developing a form validation script for an ongoing project. However, the error messages are not displaying as expected and seem to be behaving unpredictably. Requesting assistance in troubleshooting this issue would be highly appreciated.

Here is an image showcasing the unexpected behavior of the error messages for reference

Answer №1

A common issue arises when targeting elements using document.querySelector('span'), as it selects the first span in the entire document rather than within a specific container div. To address this, consider using closest() to find the closest ancestor with a specified class, which offers more flexibility if the HTML structure changes. Additionally, you can streamline class manipulation by utilizing classList for adding and removing classes without affecting other existing classes on an element.

function showError(input, message){
    const formControl = input.closest('.form-control');
    const span = formControl.querySelector("span");
    span.innerText = message;
    formControl.classList.remove('success');
    formControl.classList.add('error');
}

function showSuccess(input){
    const formControl = input.closest('.form-control');
    formControl.classList.add('success');
    formControl.classList.remove('error');
}

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

What is the best way to display my to-do list items within a React component

I'm working on a straightforward todo application using fastapi and react. How can I display my todos? I attempted to use {todo.data}, but it's not functioning as expected. Here is my Todos.js component: import React, { useEffect, useState } fro ...

Responsive navigation menus can create confusion when hover and click events overlap

Check out my HTML5 responsive, 2-level menu by clicking HERE. The menu displays submenus on hover for wide screens and on click for narrow screens (less than 768px). The JavaScript function responsible for switching the events is shown below: function ho ...

Creating a Python web scraper that utilizes Selenium and PhantomJS to extract DOM information

Attempting to extract data from a website that uses JavaScript to build the DOM, I employed both Selenium and PhantomJS. While the code provided below sometimes works, it often retrieves an empty website without executing the necessary JavaScript. Only oc ...

Div with a fixed position that is displayed on top of another following div

Having trouble with my code on this fiddle: https://jsfiddle.net/0vau6psp/. It seems to be related to the position:fixed property, but I can't seem to solve it. The issue is that the header is overlapping the main content, making it invisible. I want ...

How to extract part of a string delimited by certain characters within GET parameters?

I have a requirement to modify an iframe src attribute generated dynamically by a BrightCove video player. Specifically, I need to eliminate certain GET parameters such as width and height, so that the width and height of the parent element take precedence ...

Are there any JavaScript libraries available that can mimic SQLite using localStorage?

My current application makes use of SQLite for storage, but I am looking to switch it up to make it compatible with Firefox and other browsers. I've been considering localStorage as an option. However, I've noticed that localStorage lacks some o ...

tips for dynamically highlighting search bar after choosing a different dropdown option - vuejs

I need to filter products in my application based on name and category. To achieve this, I have included a search text box and a dropdown select box. The dropdown select box offers two options: 1. Search products by name 2. Search products by category name ...

Issue with retrieving relative time using Moment.js - fromNow()

I want to utilize moment.js to display relative time fromNow(), but I am encountering an issue where the values are being rounded and showing higher durations instead of exact completion times. For example, moment().subtract('s',110).fromNow() / ...

Changing the hue of individual pixels on an HTML canvas to a different color while maintaining their original shading

I have created a function that enables me to draw an image on a hidden canvas temporarily in order to modify colors and change everything except solid black to a specific color while preserving the original white "shade". However, when attempting to execu ...

Implementing a JavaScript function with parameters onto an element using backend code

Hey everyone, I've run into a strange issue while trying to pass string parameters to a JavaScript function from the code behind. Here is the current code snippet that I believe is causing the problem: thumbnail = "<a href = 'javascript:Remov ...

Modify section background color for every iteration in an image carousel

Is it possible to dynamically change the background color of the cd-hero section each time a new image is loaded in a simple slider on the home page? Can this be achieved by storing predefined colors in an array so that different images trigger different b ...

Exploring the implementation of JavaScript bit-shift and bit-wise operations in Java

I'm currently attempting to emulate the functionality of JavaScript bit-shift and bitwise operations in Java. Have you ever tried to accomplish this task, and how can it be done reliably and consistently even when dealing with long integers? var i ...

incorrect text alignment issue on mobile devices, potentially limited to iOS as Android has not been tested

I am experiencing an issue with the alignment of two forms on my webpage when viewed on iOS devices such as iPhone and iPad Safari. Strangely, the forms display correctly on computers (Windows and even Mac with Safari), but on mobile devices the inputs are ...

What is the functionality of the disabled attribute on an option tag within a dropdown select menu?

I am working with a code snippet that involves understanding how the attribute:disabled functions on an <option> within a <select> element! Let's say I have a dropdown for ratings and I select the 5-star option (★★★★★). Upon sel ...

Tips for managing, showcasing, and modifying checkbox controls within an AngularJS environment

I have successfully completed the saving part of the code. Below, I am demonstrating how I displayed the saved data and my attempts to edit the form upon clicking the edit button. Here is my AngularJS code: var module = angular.module('myApp&apos ...

Tips on saving an array as a variable

Can anyone help me figure out how to store a PHP variable into a JavaScript variable? var myArray; function retrieveData(id) { $.post( "main/updater.php", { id:id } ).done(function( data ) { myArray = data; }); } I&ap ...

What is the process for removing an item from a JSON file using an HTTP DELETE request in a Node.js environment?

Essentially, I have a JSON file containing user and group data and I need to delete a specific group from it. Below is a snippet of the JSON file named authdata.json: [{ "name": "Allan", "role": ["Group Admin", "Super Admin"], "group": ["Cool- ...

When using Node.js and geth together, running JavaScript code may lead to the creation of zombie processes, causing the

Currently, I am utilizing a JavaScript code that connects to the web3 package on Ethereum's JSON RPC API. This code is designed to iterate through each transaction in an incoming block. If the transaction involves an internal wallet, it sends the rele ...

After sending a post request, the form in HTML with Node.js is returning an undefined response

Upon creating an HTML <form></form> object to capture a username, email, and password, I encountered an issue where the value returned is always undefined when accessing req.body.name or any other field. It seems like the form is not functionin ...

Positioning a fixed div within a responsive div using AngularJS and Bootstrap

I'm currently working on a page layout that consists of a fixed sidebar on the left side and a main container taking up the rest of the page on the right. Inside this right-side container, which is a div, there are 2 elements. <div class="col-sm-1 ...