Adding a listener to an element within a loop

I'm currently exploring a way to add an event listener in my script.

Here's the variable I have:

var inputs = data.context.find(':input').not(':button');

Following that, I have a FOR loop where I utilize this variable to append a CSS class to certain fields:

inputs[i].className += " invalidEntry";

This method works without any issues.

However, what I aim to achieve is to also associate an event handler with these fields. This event handler should remove the mentioned CSS class whenever the values in those fields are changed.

My question then becomes - how can I attach an event listener to `inputs[i]` within the FOR loop?

Answer №1

Here is an example of how to add it:

function updateInput(){
    // 'this' refers to the element that triggered the keypress event.
    this.className = this.className.replace(" invalidEntry", "");
}
for(var i=0; i<inputs.length; i++){
    inputs[i].className += " invalidEntry";
    inputs[i].addEventListener('keypress', updateInput);
}

The updateInput function only needs to be defined once, as it can be used repeatedly since the 'this' keyword will always refer to the input element that triggered the event.

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

developing versatile paths with Node.js

app.js // Including Routes require("./routes")(app); router folder index.js module.exports = function (app) { app.use("/", require("./all_routes")); } all_routes.js var express = require("express"); var route ...

What steps do I need to take to incorporate Material UI icons into my REACT project?

After reviewing the documentation, I found it somewhat confusing with terms such as "MaterialIcon, SVGIcons, Icons". If you are interested, you can check out the link here. I am looking for a simple explanation of the process from installation to using th ...

Problem with Material UI Checkbox failing to switch states

I'm a bit confused about the functionality of my checkbox in Material UI. The documentation makes it seem simple, but I'm struggling to get my checkbox to toggle on or off after creating the component. const createCheckBox = (row, checkBoxStatus, ...

Node js server for world's warm greetings

I have been attempting to utilize Node.js for hosting a web server on a dedicated PC, but unfortunately I am unable to access it from anywhere outside of my local network. After researching online, the general consensus is that all I need to do is enter t ...

Ways to delete an attribute from a DOM element with Javascript

My goal is to use JavaScript to remove an attribute from a DOM node: <div id="foo">Hi there</div> First, I add an attribute: document.getElementById("foo").attributes['contoso'] = "Hello, world!"; Then I attempt to remove it: doc ...

The unexpected behavior in React's reconciliation process: What is causing the state to remain unchanged?

While exploring the React documentation, I came across an interesting example of resetting state: here To better understand it, I created different sandboxes to experiment with. However, I am struggling to reconcile what I observe in each of them. Each s ...

Automatic playback of the next video in a video slider

Looking to upgrade my video slider functionality - switching between videos, playing automatically when one finishes. Struggling to find a solution that combines manual control with automatic playback. My attempt: function videoUrl(hmmmmmm){ ...

Creating a form with required fields in Angular and using the ngIf directive

Update: modified the sample code to incorporate TypeScript for better clarity I have a form with various buttons for users to choose from. The submit button is initially disabled until a user selects a button. However, there's a unique requirement wh ...

Display and conceal automatically created input box using JavaScript

I am facing an issue with a form that contains a select dropdown and an input box. The input box should only be visible when the "Other" option is selected from the dropdown. The problem arises when a button clones this code, creating additional copies of ...

Retrieve the current language from a non-page component on the server side with the help of Next.js and the next-i18next

I am working on a nextjs application that utilizes the next-i18next library for internationalization. I'm struggling to figure out how to access the current language on the server-side within a component that is not a page. On the server side, you ca ...

Reducing the slide margins in impress.js?

When using Impress.js, I noticed that the default slides have a large left margin (or padding - it's hard to determine with Firefox's Inspector). I have a slide with a wide <pre> block that would fit if it were aligned to the left, but it d ...

The issue arises when DataTable fails to retrieve the ID element following a page transition

I am facing an issue with making ajax calls on focus for each text input. I am able to do it on the first page, during document ready event. However, when I navigate to another page, JavaScript is unable to parse the inputs as they were not created during ...

Angular: Design dependent on attributes

Can I customize the styling of a div in accordance with a boolean property called "isActive" on my controller using Angular? <div class="col-md-3" (click)="isActive = !isActive"> <div class="center"> <i class="fa fa-calendar"& ...

What is the best method for globally configuring the Angular moment timezone?

I integrated angular moment js into my angular application. I am looking to display the date and time based on the time zone of the user accessing the app. However, I am facing difficulty in applying the time zone globally throughout my application. https ...

Yii employs the use of quickdlgs to efficiently generate fresh entries within the CGrid view

Within my web application, I am attempting to implement an iframe button using quickdlgs to create new records. However, upon clicking the iframe button, instead of being directed to the 'create' webpage, I am presented with an empty iframe. Here ...

Tips for creating a script to calculate the population count of a 16-bit integer with either php or javascript

Looking to write a function that calculates the population count of a 16-bit integer in either php or javascript? Population count refers to the number of "turned on" bits, essentially counting the number of ones in the binary representation. For example, ...

What is the functionality of the save callback in Mongoose?

Currently in the process of learning about Mongoose's save() function for the MEAN stack. This particular function requires a callback as outlined in its API documentation: Model#save([options], [fn]) Saves this document. Parameters: [options] < ...

transfer scope variable to scope function

I notice this pattern frequently view: <input ng-model="vm.model"> <button ng-click="vm.method(vm.model)"></button> controller: function Controller() { var vm = this; this.method = function(parameter) { // perform acti ...

Overriding the w-4xl with sm:text-2xl in Tailwind CSS

Struggling to achieve responsive design on my Pages, especially with changing text size when the screen is small. I've been following all the correct steps and maintaining the right order. However, whenever I set 'sm', it seems to override a ...

Is it possible to use two onChange functions in a single text field with ReactJS?

Is it possible to have two onChange functions in a single Textfield? In my code, "onChange={ showDiv}" is a handler that shows "Direct 2" when clicked and hides upon selecting option1. The second onChange={(e) => exhandleChange(e)} is used for another ...