Verification of a Basic Form

I am currently in the process of learning JavaScript. My current goal is to figure out how to loop through an entire form and identify any errors that need to be pointed out.

The code I have put together is a mix of different tutorials that I found online, but unfortunately, it's not functioning correctly.

What I aim to achieve is to gather all elements from the form, iterate through them, and highlight any blank fields by displaying an error message on the screen either above the form or below the textboxes themselves.

This is the current version of my code. Any assistance in making this work according to my vision or providing guidance on the outlined concept would be greatly appreciated. Please keep explanations simple and concise if possible.

<!DOCTYPE HTML>
<html>
   <head>
      <meta charset="utf-8" />
   </head>
   <body>
      <form method="post" action="" id="myForm">
         <div id="validation"></div>
         <p><label>Name<br><input type="text" name="Name"></label></p>
         <p><label>Email<br><input type="text" name="Email"></label></p>
         <p><input type="submit" value="Submit"></p>
      </form>
      <script>
         var formsCollection = document.forms[0]; 
         for (var i = 0; i < formsCollection.elements.length; i++) {
             if (formsCollection.elements.value.length == 0) {
                 form.elements.input.border = "1px solid red"; 
                 form.Name.style.backgroundColor = "#FFCCCC";
             }
             return true;
         }
         document.getElementById("myForm").onsubmit = function () {
             return Validate(this);
         };
      </script>
   </body>
</html>

EDIT

<script>
  function Validate() {
     var formsCollection = document.forms[0]; 
     for (var i = 0; i < formsCollection.elements.length; i++) {
         if (formsCollection.elements[i].value.length == 0) {
             form.elements.input.border = "1px solid red"; 
             form.Name.style.backgroundColor = "#FFCCCC";
         }
         return true;
     }
     document.getElementById("myForm").onsubmit = function () {
         return Validate(this);
     };
 }
  </script>

Answer №1

Here is the full answer:

<!DOCTYPE HTML>
<html>
   <head>
      <meta charset="utf-8" />
   </head>
   <body>
  <form method="post" action="" id="myForm">
     <div id="validation"></div>
     <p><label>Name<br><input type="text" name="Name"></label></p>
     <p><label>Email<br><input type="text" name="Email"></label></p>
     <p><input type="submit" value="Submit"></p>
  </form>

<script>
 document.forms[0].onsubmit= function() {
     var form = document.forms[0];
     for (var i = 0; i < form.elements.length; i++) {
         if (form.elements[i].value.length == 0) {
               console.log(form.elements[i]);
             form.elements[i].border = "1px solid red"; 
             form.elements[i].style.backgroundColor = "#FFCCCC";
             return false;
         }
     }
 }
 </script>
   </body>
</html>

There are a few issues to address here.

  1. It seems like you are missing the i in your for loop usage.

Please change

if (formsCollection.elements.value.length == 0) {
to
if (formsCollection.elements[i].value.length == 0) {

  1. Where is the Validate function located?

You should enclose the code between

var formsCollection ... END_OF_FOR_LOOP
with function Validate(){ and }

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

Setting up NestJs with TypeORM by utilizing environment files

In my setup, I have two different .env files named dev.env and staging.env. My database ORM is typeorm. I am seeking guidance on how to configure typeorm to read the appropriate config file whenever I launch the application. Currently, I am encountering ...

Transmit the JavaScript array via AJAX to PHP server

Is it possible to transfer a JS array created using the .push function to another PHP file? I have included the code snippets for the two files involved, game.js and gallery.php. In Game.js: imgarray.push({"img_name": img_name,"x": x_value,"y": y_value,"w ...

The image is loaded correctly through the image picker, however, it is not displaying on the screen

When I click the button to pick an image from the gallery in this code, it is supposed to load the phone's gallery and display the selected image in the image component. Even though the image gets loaded properly (confirmed through test logs), it does ...

There seems to be an issue with the border displaying correctly within the div element

I am currently working on developing a tag input system, but I am encountering some CSS issues. What I am aiming for is to have a green border that surrounds and contains the 2 divs inside it, however, this is not happening as expected. You can see the fi ...

"Implementing jQuery to dynamically set the href attribute for a link when

My website features a tabbed menu that displays content from various WordPress categories including Cars, Trucks, and Buses. The active tab is randomly selected each time the page is reloaded. However, there seems to be an issue with the "View More" button ...

Error encountered in Angular $injector:unpr while attempting to initialize uibModal

I followed the ui-bootstrap tutorial to create my code. On my homepage, there is a button that triggers a modal window to open using ng-click. However, when I check the dev tools, I encounter the following error: Error: [$injector:unpr] Unknown provider: ...

The addition and deletion of classes can sometimes lead to disruptions in the DOM

I've been struggling to phrase this question for a while now. I'm working on a single-page e-commerce site that operates by modifying the HTML in divs and using CSS along with JQuery to show and hide those divs. My problem arises when, occasional ...

Trouble updating Express-Session cookie

Hello, I have been working with express.js and have encountered an issue with express-sessions. Here is how my express session is configured in index.js: app.use( session({ secret: 'idegas', resave: false, saveUninitialized: false, cook ...

Updating the parent component in React when the child component is updated: A step-by-step guide

I am currently working on a child component that consists of four checkboxes with values ranging from 1 to 4. The challenge I am facing is that every time a user clicks on one of the checkboxes, it should pass the respective value to my API to retrieve ite ...

Use JavaScript to generate an HTML element that has an attribute mirroring its text content

Trying to figure out how to create an HTML element similar to this: <option value="Replaced">by this</option> For example: <option value="ThisIsTest">ThisIsTest</option> UPDATE Using jQuery, I need to achieve something like thi ...

Exploring the magic of dynamically populating ion-options from an array

My goal is to have a service that can load and save templates. When I click on the ion-select element, I want the options to be dynamically loaded so that every saved template becomes an option instead of using hardcoded options. I attempted to use NgFor ...

Utilizing only JavaScript to parse JSON data

I couldn't find a similar question that was detailed enough. Currently, I have an ajax call that accesses a php page and receives the response: echo json_encode($cUrl_c->temp_results); This response looks something like this: {"key":"value", "k ...

Using both Promise based architecture and events in Node.js can lead to unexpected behavior and should be avoided

Currently, I am developing a nodejs application that is expected to grow in size. Despite my efforts, I have not been able to find many resources on advanced Nodejs project architecture and structure. I am wondering if it would be considered bad practice ...

Mongoose - run a function on a designated date within the document

Currently, I am developing a cryptocurrency-based betting game project. My database of choice is mongodb and I utilize mongoose for interaction with it. Within this database, I have a collection that houses documents detailing various betting games. Each d ...

Navigating React Router: Updating the page on back button press

Looking for a solution to a persistent issue. Despite various attempts and exhaustive research, the problem remains unresolved. Here's the situation: Within my React-Router-Dom setup, there is a parent component featuring a logo that remains fixed an ...

Issue with host header detected in MERN stack configuration

"proxy": "https://mango-artist-rmdnr.pwskills.app:5000", While attempting to establish a connection between my frontend and backend, I encountered an issue with an invalid host header. The backend is operating on port 5000, and the fr ...

Why does my ngFor consistently refresh while the array remains unchanged?

Issue at hand: Whenever I launch this component, the ngFor div continuously updates and causes my RAM to deplete. Typically, ngFor is triggered when the array is updated; however, in my case, the array (announcements) only updates once in the constructor. ...

Steps to show a particular row in a Vue.js API

I have a question about how to retrieve data from an API and display it in a textbox when the edit button on a specific row table is clicked. The data should include its own id along with other details. I apologize for sharing my code in this format, as I ...

What is the reason behind router.base not functioning properly for static sources while running 'npm run build' in Nuxt.js?

Customizing Nuxt Configuration const BASE_PATH = `/${process.env.CATEGORY.toLowerCase()}/`; export default { router : { base : BASE_PATH }, } In addition, there is a static source for an image in the component: <img src="/mockups/macbookpro_01. ...

Is there a way to create Angular components sourced from an external library using JavaScript?

I'm currently developing an Angular project and leveraging an external component library called NGPrime. This library provides me with a variety of pre-built components, including <p-button> (which I am using in place of a standard <button> ...