JavaScript code contains an unrecognized variable that appears outside of a for loop, which also has multiple event

I am looking to implement client-side validation using the Javascript Validation API.

Although I have created custom validation for certain fields, I now want to create a generic validation for all fields when they are left empty. In my attempt to do so with a for loop, I encountered an error when trying to access the variable [i] outside of the loop: Uncaught TypeError: Cannot read property 'value' of undefined

This is the code I have written thus far.

//Test
var test_field = document.querySelectorAll(".um-form-field");
var i;

  for (i = 0; i < test_field.length; i++) {
            
            test_field[i].addEventListener('keyup', test_function, false);
            test_field[i].addEventListener('click', test_function, false);
            test_field[i].addEventListener('invalid', test_function, false);
            
            console.log(test_field[i].value);//this works every time i click or type a field!


  function test_function (event) {
            console.log(test_field[i].value);//This tells me an undefined variable every time I click on a field

            }
  }

EDITED 24/12: Appreciate the assistance from everyone. I have ended up using event.target as suggested in the comments.

This is my updated code (I'm still working out some issues with setCustomValidity):

var all_fields = document.querySelectorAll(".um-form-field");
var i;
for (i = 0; i < all_fields.length; i++) {
            
    all_fields[i].addEventListener('keyup', field_function, false);
    all_fields[i].addEventListener('click', field_function, false);
    all_fields[i].addEventListener('invalid', field_function, false);
            
function field_function (event) {

if (event.target.value.length == 0) {
        event.target.style.background = "#eb91ae";
        event.target.setCustomValidity("error");
        divError.style.display = "block";
        divError.innerHTML = "You must complete this field";
        event.target.parentElement.appendChild(divError);
} else {
        event.target.style.background = "#9deb91";
        event.target.setCustomValidity("");
        divError.style.display = "none";
}
}
}

Answer №1

It seems like there is an issue with your code. After the iterable for...loop, the variable i will reach the end value, which means that i will be equal to test_field.length. As a result, the test_function will look different when it executes:

 function test_function (event) {
            console.log(test_field[test_field.length].value);

            }

To quickly fix this, you can try the following approach:

var test_field = document.querySelectorAll(".um-form-field");
test_field.forEach(field => {
    field.addEventListener('keyup', test_function, false);
    field.addEventListener('click', test_function, false);
    field.addEventListener('invalid', test_function, false);
});

function test_function (event) {
    console.log(event.target.value);
}

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

Struggling to make EJS button functional on the template

I am currently facing an issue with a loop that populates a webpage with multiple items, each containing an image, text, button, and a unique ID associated with it. Although I have written a function to retrieve the ID and plan name when the button is clic ...

Utilize Jquery to toggle text input forms based on radio button selections

I have a group of text inputs labeled with the class 'bankinput'. Alongside them, I have two radio buttons generated by asp.net helpers. The ids assigned to these radio buttons in the generated html are 'Cheque' and 'Draft'. F ...

How to efficiently deliver a document to a user using the MEAN stack

The express controller code snippet I'm working with involves creating a CSV file and sending it back to the user: // Correct file path and write data var currentDate = new Date(); var storagePath = path.join(__dirname,'../../public/reports/&apo ...

Is there a way for me to retrieve the value from an input, round it up to the nearest even number, and assign it to a new variable?

I am working on a project that involves two text boxes and a drop-down menu for providing rates. The values in the text boxes are given as inches. I want these inputs to be taken as values, rounded up to the next even number, and then set as variables. How ...

Transferring files from the android_asset directory to the SD Card

I am trying to play video files that are packaged within a Cordova application. My goal is to transfer these files from the android_asset folder to the SD card using the File API in JavaScript. However, I am encountering difficulties in accessing this fol ...

Is it a breach of separation of concerns to validate using ng-pattern?

I have a requirement in Singapore to validate contact numbers entered by users. The number must start with 6, 8, or 9 and should have a total of 8 digits. I am currently utilizing ng-pattern on an input field with a regex solution, but I am concerned abo ...

Utilizing Node.js, delete the author from the database and then use a GET request to display all

Exploring node and express for the first time. I've been working on an example that utilizes GET and POST methods, but now I want to implement DELETE function to delete a book based on its title. Additionally, I need to introduce another GET method to ...

Error: The term "require" is not recognized in the context of the React

After creating my own React component as an NPM package and publishing it on NPM, I encountered an error when trying to import and use it in other Create React App (CRA) projects. The error occurs when running npm start in the command line. See the screens ...

Interactive auto-suggest feature in JavaScript while typing

I am currently working on an HTML page that includes a text field for users to input text in any language. I have a javascript file containing a list of world languages that I want the text field to autocomplete from. Despite linking the javascript file to ...

Adjust the width of the iframe

I've been tasked with customizing a customer's website, and the admin has given me permission to use my own JavaScript file (myScript.js). How can I manipulate the iframe width from 160px to 200px using DOM Operations? <div id="iframeDiv& ...

Attempting to update using the .put() method proved futile as it has been deprecated. I then attempted to use the updateOne

.put(function(req,res) { console.log(req.body.content); Article.update( {title:req.params.specificarticle}, {title:req.body.title, content:req.body.content}, {overwrite:true}, function(err) { if(!err){ res.send("Article has been updated successfully ...

Can a mutable static class variable be created in JavaScript?

I have an idea similar to this concept: class Example { static var X; static setX(value) { this.X = value; } static getX() { return this.X; } } This allows the variable to be stored within the class and easily modified ...

calculating the mean of elements within a three-dimensional array in the R programming language

I need to calculate average values from a list containing 3-D arrays as elements. For example, where ind1 represents an element in a 3-D array: >data$ind1 , , rep1 [,1] [,2] [,3] [1,] 58.93456 6.3580551 269.8844 ...

Trouble with Colorbox loading? Here's a quick fix!

I'm experiencing a frustrating issue. Although I have successfully used colorbox in the past, it is not working on a new website I am developing. All necessary files, including jquery and colorbox, are located in the same directory as the html file. ...

Can diverse array elements be divided into separate arrays based on their object type in JavaScript?

Looking to create new arrays based on objects with similar attributes from an existing array? Here's how: Starting with this [ {name: "test", place: "country"}, {name: "walkAndEat", Long: 100, Lat: 15, Location: "place name"}, {name: "te ...

The npm script for running Protractor is encountering an error

Currently, I am facing an issue while trying to execute the conf.js file using an npm script. The conf.js file is generated within the JSFilesRepo/config folder after running the tsc command as I am utilizing TypeScript in conjunction with protractor-jasmi ...

Ways to conceal a div element depending on the selection made in an AngularJS dropdown menu

Is there a way to dynamically hide a div based on a selected dropdown option? Here is the code snippet I have come up with: <div> <p>Course Type</p> <div> <select name="student-type" id="student-type&q ...

Is it necessary to configure Webpack or use a plugin to remove console.log() statements by default in an Angular Application, or does it do so automatically?

Welcome to my first post! I hope I can effectively communicate the question and the background that led me to ask it. I am relatively new to web programming, with about 1 and a half years of experience working with Java, JavaScript, and TypeScript using An ...

Adding client-side scripts to a web page in a Node.js environment

Currently, I am embarking on a project involving ts, node, and express. My primary query is whether there exists a method to incorporate typescript files into HTML/ejs that can be executed on the client side (allowing access to document e.t.c., similar to ...

What are the steps for turning off chart animations in LightningChart JS?

Is there a way to turn off the animations in LightningChart JS charts? ...