How to Display JavaScript Error Messages Beside an HTML/JSP Input Field with CSS

Hey there! I've got a simple CRUD input form with Javascript validation. When an error occurs, the error message pops up below the input field in red text. I've tried various methods like floats and adjusting margins, but nothing seems to work.

The code is on a different computer, but basically, the JavaScript checks for a span value in the HTML. If it's not there, it creates the error message and sets its properties using CSS.

Here's a snippet of the HTML:

<label for="fName">First Name:</label>

<form:input type="text" name="fName" id="fName" path="fName"/>

<div id = "fName.errorField"><font color="red"><form:errors cssClass= "error" path="fName" /></font></div><br />

A piece of the JS:

if(document.getElementById('fName.errors') == null){

newSpan.id = "fname.errors";

newSpan.className = "error";

document.getElementById('fname.errorField').appendChild(newSpan);

newSpan = document.createElement("span");

}

function validateFName() {

var alphaChar = /^[a-zA-Z]+$/;

var nameFChek = document.input.fName.value;



if (nameFChek == ""){

document.getElementById("fName.errors").innerHTML = "This field is blank (fname)";

return false;

}

And here's my current CSS:

form { width: 800px;}

label { float: left; width: 150px;}

input[type=text] { float: left; width: 250px;}

.clear { clear:both; height: 0; line-height: 0;}

.floatright { float: right;}

Answer №1

It appears that you are dynamically creating a new span element and inserting it into the DOM using vanilla JavaScript. If your project is growing in size, I suggest utilizing a validation tool such as jQuery Validate for error checking: http://jqueryvalidation.org/

Even if you have already written a substantial amount of code, it would be beneficial to integrate a plugin for future enhancements.

You may also want to explore the demo's CSS at http://jqueryvalidation.org/files/demo/.

Without a functional jsfiddle link, pinpointing the issue within your code becomes challenging.

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 transfer a JavaScript variable to a PHP file and then store it in a PHP variable?

I am working on a webpage that displays multiple images, each of which can be replaced by another image in the same location. Adjacent to each image is a form where users can upload the new image. One important requirement is that the newly uploaded image ...

initiating a submission upon the occurrence of an onchange event on an input field of type "file"

I have encountered an issue while trying to submit a form using the onchange event of an input element with type file. The problem is that it submits an empty form even when a file has been chosen. Here is the code snippet: var form = document.createElem ...

Dropdown functionality in JavaScript and Bootstrap

Struggling with getting the bootstrap dropdown to change class on click? Don't worry, I've managed to make it change from "+" to "-", but now I'm facing an issue. When I click on the second dropdown, the one I clicked before doesn't cha ...

Invoking Javascript Functions using their names

Suppose I have the following element on my page... <span data-function="DoSomething">Click</span> ... and then add the following to my page header... $(document).ready(function() { $('[data-function]').each(function() { ...

I've noticed that whenever I attempt to update my array in useState using React Hooks, it does indeed work. However, I've also observed that the array seems to

import React,{useState} from "react"; const friendsList = [ { name:"Jack", age: 30, }, { name:"Emily", age: 28, }, { name:"Alex", age: 25, }, ] ...

Encountering a CastError in Mongoose validation where the value fails to cast to undefined

I encountered a forbidden message while attempting to save data into the database. CastError: Cast to undefined failed for value [ {"product":{"supplierId":{"undefined":"rfytr"}}}, {"product":{"supplierId":{"$empty":"rfytr"}}} ] at path "condition" ...

Click the icon to introduce a fresh row into the table

I have embedded a table with a "plus" font awesome icon. <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorig ...

You need to hit the F5 key to activate the bean feature on the Firefox browser

Recently, I've come across a strange issue. I have a button that is supposed to call a method in a bean which redirects me to another page. However, it's not working as expected (it doesn't trigger the method) unless I press F5. Strangely, t ...

Incorporating Bootstrap JS into Next.js

Currently, I am in the process of learning next.js and experimenting with incorporating Bootstrap into my projects. To begin, I initiated a new project using npx create-next-app@latest my-app, utilizing the newly created "app" directory structure. Follow ...

display picture on a Vue-powered webpage

<main id="meals"> <h3 style="text-align: center;">Week 1 - Day 1</h3> <h6>{{mealType}} ( {{selectedItems}}/{{maxSelection}} selected )</h6> <div class="grid"> ...

Preventing dragging in Vis.js nodes after a double click: a definitive guide

Working with my Vis.js network, I have set up an event listener to capture double clicks on a node. ISSUE: After double-clicking a node, it unexpectedly starts dragging and remains attached to the mouse cursor until clicked again. How can I prevent this b ...

Ways to avoid a bootstrap column from wrapping onto a new line when the parent width is decreased

https://i.sstatic.net/gKdAN.png I attempted to decrease the form width by applying padding on both sides of the form using 'px-5'. However, when I implemented this change, the column holding the '#lastName' input shifted to a new line. ...

Element imitating the edge of the screen extending to the edge of the container

Looking to customize a website design (utilizing bootstrap 4) with a gradient line that starts from the title and stretches all the way to the left edge of the container. While I have managed to set this up, the full gradient effect is not visible. To addr ...

What is the best way to make an element disappear 5 seconds after the mouse has stopped hovering

#section1 { display: block; } #section2 { display: none; } #container:hover > #section2 { display: block; } <div id="container"> <div id="section1">Section1</div> <div id="section2">Section2</div> </div> ...

Wordpress team exhibition

Does anyone know how to create a Team showcase slider in Wordpress? I have been using slick slider, but I'm looking for a way to add team members easily through a plugin rather than manually. I found an image of what I want it to look like. Can any ...

Steps for eliminating an element upon the second click:

I am faced with a challenge where I need to dynamically add elements to a container on the first click and delete them on the second click. I feel like I am complicating things unnecessarily and there must be a simpler and more elegant solution available. ...

Utilizing NodeJS and Express to enhance the client side for showcasing an uploaded file

My knowledge of nodeJS, AJAX requests, and routing is still in its infancy. After following a tutorial on nodejs and express examples, I managed to get everything working on the server-side. However, I'm facing difficulty displaying the uploaded file ...

Sequelize JS - Opting for the On clause in join operations

Seeking guidance on selecting the appropriate ON clause for a join. I am working with two tables - packages and users. The package table contains two fields/columns (owner_id, helper_id) that serve as foreign keys to the same users table. My goal is to per ...

Using AJAX and PHP to upload form data to a MySQL database

My custom index page: <html> <head> </head> <body> <form name="form1" action="submit.php" method='POST'> <select id="dropdown1" name="country" onchange="window.getStates()"> <option> Select Country</ ...

Validating JSON against a JSON schema using JavaScript

My current task involves validating approximately 100 JSON Objects against a specific JSON schema to ensure that all fields and their types align with the schema requirements. Initially, I attempted to use a JSON schema generated from a website. However, ...