Issue with element.onchange not functioning properly with a group of elements

Exploring my Form and Question classes has been an interesting journey. In my "Form" class, I store an array of questions and utilize a method called render() to display each one.

    render() {
        let htmlElement = document.getElementById("formBody");

        let id = Question.GenerateID();
        htmlElement.innerHTML += `
                <div class="p-2">
                    <input type="text" class="input-transparent w-100" id="${id}.t" value="${this.Title}" placeholder="Unnamed question">
                </div>`;

        /**
         * @param {int} id
         */
        let questionNameChange = function(id) {
            this.Title = document.getElementById(id + ".t").value;
        };

        document.getElementById(id + ".t").onchange = questionNameChange.bind(this, id);
     }

Pictured below is the form that showcases these elements.

In troubleshooting, I've encountered an issue related to the element.onchange event which helps me modify question titles.

Despite adjusting input text fields for various questions, the title only updates on the last rendered question.

Could there be an error in my approach?

Answer №1

If you find that the onchange event is not binding properly, consider delaying it until the element has been fully inserted into the DOM. One way to do this is by wrapping the onchange function assignment in a setTimeout:

  setTimeout(function() {
        document.getElementById(id + ".t").onchange = questionNameChange.bind(this, id);
  })

Take a look at this functional example:

let Question = {GenerateID: () => Math.floor(Math.random() * 100)}
class MyClass {
  constructor(){
    this.Title = 'my title'
  }
  
  questionNameChange(id) {
    this.Title = document.getElementById(id + ".t").value;
    document.getElementById(`${id}-label`).innerHTML = this.Title
  }

  render() {
        let htmlElement = document.getElementById("formBody");

        let id = Question.GenerateID();
        htmlElement.innerHTML += `
                <div class="p-2">
                    <input type="text" class="input-transparent w-100" id="${id}.t" value="${this.Title}" placeholder="Unnamed question">
                    <label id="${id}-label"></label>
                </div>`;

        setTimeout(() => {
          document.getElementById(id + ".t").onchange = () => {
            this.questionNameChange(id)
          }
        })
        
  }   
}

$(() => {     
  let myClass = new MyClass()
     myClass.render()
     myClass.render()
     myClass.render()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="formBody">

</form>

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

Creating a 24-hour bar chart using Flot Javascript, showcasing data points at each hour mark

I am attempting to create a 24-hour bar graph using Flot Charts, with a value corresponding to each hour. It seems that Flot utilizes epoch time for hour values. However, after running the code below, I encounter an issue where the chart does not display a ...

Tips for setting a threshold in a highcharts ng chart

I am struggling with setting the threshold to zero on a simple line chart using Highchart ng. According to the Highcharts API, the property should be plotOptions.series.threshold. However, despite following advice from this source, I can't seem to get ...

What could be causing my React Router component to display incorrect styling?

While working with react-router, I encountered an issue where the text from the routed page started appearing in the navbar. Even though I separated it as its own component and it functions correctly, this specific problem persists. As a newcomer to React, ...

Issue with updating data variable from watcher on computed property in Vue.js with Vuex

Snippet: https://jsfiddle.net/mjvu6bn7/ I have a watcher implemented on a computed property in my Vue component. This computed property depends on a Vuex store variable that is set asynchronously. Despite trying to update the data variable of the Vue comp ...

Having trouble installing $ npm i mini-css-extract-plugin. Any ideas on what might be causing the issue?

There seems to be an error in my setup. I am using Visual Studio Code with gitBash. $ npm i mini-css-extract-plugin npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-p ...

Using NodeJS and Express: redirection fails to load the specified endpoint

My current project involves a simple e-commerce web application running on localhost built with nodejs and express. Admins are required to register in order to gain access to functionalities such as adding, editing, and removing products from the product l ...

Create JavaScript code with PHP

Looking to dynamically generate the column definitions for a Datatable. Here are the columns: "columns": [ { "data": "id", "orderable": false }, { "data": "code" }, { "data": "name" }, { "data": "created", " ...

What is the default behavior for an invalid select option in Angular 2 model-driven forms?

Is it possible to create an invalid default select option in an Angular 2 model-driven form? I want to do something like the following: <select name="DateExpiryMonth" [(ngModel)]="model.DateExpiryMonth" ngControl="dateExpiryMonth" required> < ...

Is there a way to identify when a fresh google instant page appears?

I am currently developing a browser extension that requires making a call when a new Google instant page is loaded and then modifying the results, similar to SEOQuake. One problem I encountered is that if a user pastes a link directly into the URL field a ...

Discovering the world of Promises in TypeScript and understanding how to return specific types

Transitioning from coding in Clojure for the past two years to TypeScript has been an interesting journey. However, I've hit a bit of a roadblock today. The issue lies with my interface: interface ICustomer { id: number, first_name: string } I ...

Having trouble with the "initSdk" property being undefined in your React Native Appsflyer integration?

I'm currently facing an issue while trying to integrate AppsFlyer into a react native application. The error I am encountering is "Cannot read property 'initSdk' of undefined" Initially, I imported the react-native-appsflyer module as shown ...

Can multiple `npm install` commands run at the same time?

Is it possible to have concurrent runs of npm install, or will they conflict on shared resources and create potential race conditions? Analyzing the code might not provide a clear answer, but for those working on developing npm, this is likely an implicit ...

Utilizing a URL to dynamically update the content within an I-Frame

One day, I made the questionable decision to use i-frames to load pages on my website in order to keep a sidebar on the main page without having to constantly make changes. In hindsight, I should have done the opposite and put the sidebar in the i-frame. N ...

Creating an HTML element that can zoom, using dimensions specified in percentages but appearing as if they were specified in pixels

This question may seem simple, but I have been searching for an answer and haven't found one yet. Imagine we have an HTML element with dimensions specified in pixels: <div style="width:750px; height: 250px"></div> We can easily resize i ...

JavaScript xPath is ineffective at providing a return value

Trying to work through an issue with xPath and I am new to this concept. Any guidance or assistance in JavaScript would be greatly appreciated. Here is the simple HTML document that I have: <!DOCTYPE html> <html> <head> < ...

Looking to modify the contents of a shopping cart by utilizing javascript/jQuery to add or remove items?

I'm dealing with a challenge on my assignment. I've been tasked with creating a Shopping Cart using Javascript, HTML5, and JQuery. It needs to collect all the items from the shop inside an Array. While I believe I have most of it figured out, I a ...

Challenges Encountered with Array.every

Exploring JavaScript default false values, I attempted some manipulations but encountered an issue with Array.every. Can anyone assist me in resolving this? ...

Exploring the combination of Babel and Next.js: Integrating custom scripts into a project

Hello, I am currently learning next.js and facing a common issue that I need help with. I have created my own ES6 JavaScript library and now I want to convert it to babel so I can use it in my next.js application. Is there a way to configure babel for sp ...

Sending a Javascript string to PHP

I am trying to send a JavaScript string to PHP immediately after the code within the script tag. <script type="text/javascript"> var myvar = "mytext" ; <?php echo myvar ; ?> </script> Unfortunately, this approach is not functioning ...

Performing an AJAX call in Rails 4 to update a particular value

I have a voting button on my website that displays the number of votes and adds an extra vote when clicked. I want to implement Ajax so that the page doesn't need to refresh every time a user votes. However, I am new to using Ajax with Rails and not s ...