Challenges with handling form elements in JavaScript

I'm currently developing a project and facing challenges in implementing input validation for a form. My goal is to ensure that the form only gets submitted and redirects to a specific URL if all requirements are met. To achieve this, I am utilizing Javascript for validation checks. Despite having no apparent errors in the console, when I attempt to submit the form with empty fields, it proceeds without any hindrance.

// Form Controls

const form = document.getElementById('form');
const username = document.getElementById('username');
const room = document.getElementById('room');

// Display input error message
function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = 'form-control error';
  const small = formControl.querySelector('small');
  small.innerText = message;
}

// Show Success outline
function showSuccess(input) {
  const formControl = input.parentElement;
  formControl.className = 'form-control success';
}


// Validate required fields
function checkRequired(inputArr) {
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      showError(input, `${getFieldName(input)} is required`);
    } else {
      showSuccess(input);
    }
  });
}

// Retrieve fieldName
function getFieldName(input) {
  return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}

// Event Listeners

form.addEventListener('submit', function(e) {
  e.preventDefault();

  checkRequired([username]);
});
<!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">
  <link href="../static/style.css" rel="stylesheet">
  <title>ChatR</title>
  <script src="{{ url_for('static', filename='scripts.js') }}"></script>
</head>

<body>
  <div class="container-head">
    <div class="header">
      <h1>MyApp</h1>
    </div>
  </div>

  <div class="container">
    <form action="{{url_for('chat') }}" class="form" id="form" method="POST">

      <div class="form-control">

        <input type="username" id="username" name="username" placeholder="Enter username">
        <small>Error Message</small>
      </div>
      <div class="form-control">

        <input type="room" id="room" name="room" placeholder="Enter room">
        <small>Error Message</small>
      </div>

      <button type="submit" class="btn btn-big">Start Chat</button>
    </form>

  </div>

</body>

</html>

New Code that works:

// Validate required fields
function checkRequired(inputArr) {
  var success = true;
    inputArr.forEach(function(input) {
      if (input.value.trim() === '') {
        success = false;
        showError(input, `${getFieldName(input)} is required`);
      } else {
        showSuccess(input);
      }
    });
    return success;
}  

// Check input length
function checkLength(input, min, max) {
  var success = true;
    if(input.value.length < min) {
      showError(input, `${getFieldName(input)} must be at least ${min} characters`);
      console.log(input);
      success = false;
    } else if(input.value.length > max) {
      showError(input, `${getFieldName(input)} must be less than ${max} characters`);
      success = false;
    } else {
      showSuccess(input);
    }
    return success;
}

// Retrieve fieldName
function getFieldName(input) {
  return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
  
// Event Listeners
  
form.addEventListener('submit', function(e) {
  e.preventDefault();
    
  if(checkRequired([username, room]) && checkLength(username, 3, 15)){
    form.submit();
  }      
          
   
});   

Answer №1

I have implemented some updates to the code in order for it to automatically submit upon successful validation.

The primary modification involves having the checkRequired function return either true or false, signifying the outcome of the validation process.

Additionally, I have incorporated a check within the submit event listener to verify the validity status and proceed with form submission if deemed valid.

// Function to validate required fields, returning true/false.
function checkRequired(inputArr) {
  var success = true; // Assume initial success
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      success = false; // Mark as unsuccessful if any field fails
      showError(input, `${getFieldName(input)} is required`);
    } else {
      showSuccess(input);
    }
  });
  return success; // Return overall validation result
}

// Event Listeners

form.addEventListener('submit', function(e) {
  e.preventDefault();
  // Proceed with form submission only if validation passes
  if(checkRequired([username, room])){
    form.submit();
  }
});

On a side note, it could be beneficial to include the room element in the array of inputs undergoing validation.

Answer №2

The issue at hand lies in the fact that the element is not present in the DOM while the script is executing, causing it to run only after the DOM has finished loading. The solution to this problem is to include the following line at the beginning of scripts.js

document.addEventListener("DOMContentLoaded", () => {

// All of scripts.js should be placed within this section

// Ending with this
})

By doing so, the script will wait for the DOM to load before checking if it's ready, ensuring that your script functions as intended.

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

Streaming audio from a microphone to speakers on Ubuntu using HTML5

Currently diving into html5 and eager to experiment with playing back what I say on a microphone through speakers. Here is the JavaScript code I've put together: navigator.getUserMedia = navigator.getUserMedia ||navigator.webkitGetUserMedia || naviga ...

Having difficulty applying parseFloat directly following a JSON Stringify operation

There's a specific line of code I'm working with that reads -- let longitude = JSON.stringify(place.lon); After calling alert(longitude), I receive the output "44.54321". However, my intention is to retrieve just the number itself, so I attempt ...

Exploring the world of two-dimensional arrays in D3 programming

I am interested in visualizing data obtained from the census data API, specifically from the ACS survey. The data is not in a typical JSON format, but rather as a two-dimensional array. It appears like this: [ [ “POPULATION”, “DATE”, ...

The asynchronous JavaScript function is successfully printing data, however it is encountering an error where it returns 'undefined'

Struggling with asynchronous calls, I've realized this question has been answered many times before. Despite trying numerous suggested approaches without success, I would truly appreciate any help. Progress has been made recently, but I still consider ...

Angular Promise not executing in a synchronous manner

In the javascript controller, I have a code snippet that consists of two separate functions. While these functions work individually and asynchronously when triggered from the view, my goal is to execute them synchronously on page load. This is necessary b ...

Adjusting the viewer.js script

In order to view my pdf files using Mozilla's pdfjs plugin, I currently pass a query parameter to viewer.html like this: http://localhost/MyProject/viewer.html/?file=file.pdf Although this method works fine for me, I have a unique requirement for my ...

Error: Unable to locate module '@/components/Header' in Next.js project

I'm currently facing an issue while working on my Next.js project. The problem arises when I attempt to import a component into my 'page.js' file. In the 'src' folder, I have a subdirectory named 'components' which contai ...

Dealing with checked input type='checkbox' in React - A guide

Having a set of checkboxes, some already checked and some to be updated by the user. The issue here is that while the checkboxes render correctly initially, they do not change upon clicking. The 'checked' value does get updated when onChange is t ...

Ways to adjust your selection to the space or new line before or after

$('button').on('click', function(){ const selection = window.getSelection(); selection?.modify('move', 'backward', 'word'); selection?.modify('extend', 'forward', 'to the next space ...

Adding information to an HTML table using JQuery

Is there a way to incorporate JSON data into an HTML table? The JSON data follows this format: https://i.stack.imgur.com/lzdZg.png This is the desired HTML table structure: <table class="table table-bordered table-hover "> ...

Retrieving information from a database by employing AngularJS with the assistance of PHP

I am a beginner in using AngularJS and I am trying to retrieve data from a database using PHP. Here is the code I have tried: <html> <head> <script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.2 ...

Is it possible to use jQuery validate for remote parsing with two fields in a single call

Currently, I am facing an issue while trying to parse two values using jQuery's validate plugin to compare with an SQL database. The DateReceived value is successfully parsed, but the CentreID value always appears as null. Below is the code snippet I ...

Utilizing the $.ajax method to navigate to a webpage displaying only the results that correspond to the value in the json data

I'm in the process of creating a single page application that utilizes $.ajax. Here is the JSON data: { "restaurants": [ { "id": 1, "name": "Denny's", "location": "Los Angeles", "cuisine": "American", "image_ ...

Guide to triggering React Material-UI modal and filling it with data from an Ajax request when a button is clicked

Despite my efforts to find a similar question, I couldn't come across one. My apologies if I overlooked it. Currently, I am working on a React Material-UI project to develop a basic web application. Within this application, there is an XGrid that disp ...

The values of variables persist even after refreshing the page

let quote; let author; // Establishing the Get Method for the Root Route in ExpressJS app.get('/', (req, res)=>{ res.render('home', { quote: quote, writer: author }); }); // Configuring the Post Method for t ...

What is the process for generating an Electronic Program Guide for television?

Welcome to the forum! I'm a front-end developer at a company for 6 months now, currently working on a TV app. It's my first experience in this field and I'm facing some challenges, particularly with creating an epg for the app. Unfortunately ...

Ways to bring in external javascript files in reactjs

I'm currently working on a form that requires the user to input their location. To achieve this, I have integrated the npm package react-geosuggest-plus. However, I want to avoid including <script src="https://maps.googleapis.com/maps/api/js?key=AI ...

Typescript Error: lib.d.ts file not found

Recently, I experimented with Typescript and utilized the Set data structure in this manner: var myset = new Set<string>(); I was pleasantly surprised that there was no need for additional libraries in Typescript, and the code worked smoothly. Howe ...

"Enhance your user experience with an interactive AngularJS dropdown menu featuring search and tree

I need to develop a custom control or directive that includes a dropdown list, search box, and tree view, as shown in the image below. When the dropdown list is clicked, it should display the search box and tree view. Selecting an item from the tree view s ...

What is the technique for filtering multiple values using the OR operation in ng-model functions?

Currently, I am using an ng-modal labeled as "myQuery." At the moment, there are two filters in place that look like this: <accordion-group heading="" ng-repeat="hungry_pets in Pets" | filter:{hungry:false} | filter:{name:myQuery}" ... > I have ...