Utilizing the Onchange Event with Multiple Input Fields in Vanilla JavaScript

I'm working on a website where multiple inputs need to be created dynamically using createElement. Each input can have its own class, id, and other attributes.

The main objective is to automatically calculate the overall price whenever a user adds a new input (such as the amount of products). This should be done without requiring any additional clicks, with the calculation being based on the product price multiplied by the quantity entered in the input field.

While I could share the code, I believe an image would better illustrate the concept. You can view it here: https://i.stack.imgur.com/c33KZ.png

I am looking for guidance on how to implement this functionality using onchange with getElementByTagName. An example would be greatly appreciated. Thank you!

Answer №1

To optimize your event handling, consider using event delegation. By focusing on a common ancestor element where events will bubble up to from child elements, you can reduce the number of listeners needed. I recommend listening for the "input" event which captures any changes made by the user:

document.addEventListener("input", function() {
    // perform calculations here:
});

This approach allows you to simplify your code by attaching just one listener.

Answer №2

Here is an example of how you can achieve this:

function updateValue() {
  // Update value function
}
const allInputs = [...document.getElementsByTagName('input')];
allInputs.forEach(input => input.addEventListener('click', updateValue));

Answer №3

Using classes is a more efficient way to handle inputs, rather than applying the same function to all of them. If you're looking for an example, here's something that might help:

function addInputListener(input) {
    //@todo Replace this with your own data
    let row = input.parentElement.parentElement;
    let overallPriceElement = row.querySelector('.overall-price');
    let price = parseInt(row.querySelector('.price').innerText);
    let calcEvent = function() {
        //@todo Enter your calculation function here
        if (this.value > 0) {
            overallPriceElement.innerText = (price * this.value).toString();
        } else {
            overallPriceElement.innerText = "No products yet";
        }
    };

    input.addEventListener('input', calcEvent);
    calcEvent.call(input); // call() used to add input context
}

// Using a class is preferred over a tag for functionality
let inputs = document.querySelectorAll('.amount');

for (let i = 0; i < inputs.length; i++) {
    let input = inputs[i];
    addInputListener(input);
}
<table>
    <thead>
    <tr>
        <th>#</th>
        <th>Name</th>
        <th>Price</th>
        <th>Amount</th>
        <th>Overall Price</th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <td>1</td>
        <td>Bread</td>
        <td class="price">3</td>
        <td><input type="number" class="amount"></td>
        <td class="overall-price"></td>
    </tr>
    <tr>
        <td>2</td>
        <td>Bread</td>
        <td class="price">10</td>
        <td><input type="number" class="amount"></td>
        <td class="overall-price"></td>
    </tr>
    <tr>
        <td>3</td>
        <td>Bread</td>
        <td class="price">30</td>
        <td><input type="number" class="amount"></td>
        <td class="overall-price"></td>
    </tr>
    </tbody>
</table>

To apply the addInputListener(input) function each time you create a new row, simply pass the newly created input using createElement to these listeners.

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

Ensuring Package Security in NodeJS and NPM

Given the immense popularity of NodeJS and how NPM operates, what measures can be taken to prevent the installation of insecure or malware-laden packages? Relying solely on user feedback from sources like StackOverflow or personal blogs seems to leave a si ...

The dimensions on Next.js pages exceed those of the viewport by a significant margin

I have recently encountered a perplexing issue where the dimensions of my webpage appear to be 2.7 times larger than the viewport, even when there is no content or styles applied. The strange part is that it seems as though the page has been scaled up, eve ...

Placeholder variable not specified in radio buttons

I am currently facing challenges applying validations to radio buttons in Angular. Normally, I create a #templateRefVariable on the input for other input types, which allows me to access the NgControl and use properties like touched. My goal is to set the ...

Is there a way to turn off predictive text for reCAPTCHA on my mobile device?

Using reCAPTCHA on a sign-up form can get frustrating on mobile devices, with constant dictionary word suggestions while typing. I am aware of how to disable this feature for normal input fields by adding attributes through JavaScript, but shouldn't ...

Navigate the JSON object at predetermined intervals, such as in the case of movie subtitles

Apologies if the title is not specific enough, open to any suggestions for improvement. Here's my issue: I have a JSON file (presented here as a JavaScript object) that contains subtitles for a movie. My goal is to display the text exactly as it appea ...

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 ...

Ensure that the assistant stays beneath the cursor while moving it

I am currently working on creating a functionality similar to the 'Sortable Widget', but due to some constraints, I cannot use the premade widget. Instead, I am trying to replicate its features using draggable and droppable elements: $(".Element ...

Leveraging JavaScript within the Selenium JavaScript Executor

I am trying to check if the required text is visible on the page, but I am unable to use the gettext() method from Selenium WebDriver due to a permission exception. As a workaround, I have created a JavaScript script to compare the text. String scriptToE ...

Ways to display or conceal information depending on the dropdown choice

In my Angular project, I am dealing with a dropdown menu that is followed by some data displayed in a div element. component.html <select class="form-control" id="power" required> <option value="" disabled selected ...

Strategies for transferring retrieved data to the getServerSideProps function

I am currently utilizing the Context API to retrieve data and then pass that data to the getServerSideProps function, but encountering the following error: The React Hook "useContext" is being called in a function "getServerSideProps" that is neither a Re ...

Can a package-lock.json file be created without running an npm install command?

Is there a way to create only a package-lock.json file without having to redo the npm install process? I'm looking to generate the lock file without reinstalling any of the package files. Is this achievable? ...

html line breaks $.parseJSON

Within my website, I am currently utilizing a TinyMCE window. The method involves PHP fetching an entry from the database, decoding it as JSON, and then having in-page JavaScript parse it. However, issues arise when there are elements like style='colo ...

Node.js is having trouble locating a module that has been installed

Upon transferring my node.js application to a different PC (where it functioned flawlessly on the development machine) and manually installing all the necessary dependencies, I encountered an error when attempting to run it: C:\Users\myself>n ...

Trouble with image click event in jQuery/JavaScript

I am having trouble with my HTML and JS code. I have added images to my HTML page and want to make it so that when the image is clicked, an alert box pops up. However, for some reason, my JavaScript isn't working as expected. Here is a snippet of my ...

Retrieve the values from multiple columns within a jqgrid row

Is it possible to retrieve both the first column value and the second column value from a jqgrid row? In my other program, I am currently using this code to obtain the first value of the row: $("#tblTallySheet").jqGrid('getGridParam', 'selr ...

Guide to verifying the update of user information with sweet Alert on ASP MVC

I'm currently working on an ASP MVC web application that involves using stored procedures with SQL Server. My goal is to implement a confirmation alert (Sweet Alert) to confirm the data update for a logged-in user. The code for editing works fine wi ...

Sending data through ajax to PHP on separate pages is a common practice

Here is where I choose my preferred option Company Name<br /> <select id="company" name="selected"> <option value="">Option A</option> <option value="">Option B</option> </select> When I click this, a mo ...

retrieve the status of a checkbox in a dynamically generated element

I'm currently working on integrating the YouTube API into my app in order to display a dynamic list of cards. The cards are stored in a variable and then added to a playlist container using an each function. Each card contains a toggle switch for use ...

Steps for dynamically loading the content of a Bootstrap 4 Modal

I am currently in the process of developing a website that will showcase a wide range of images. The design is set up as a landing page with all content contained within the main HTML page - there is only an index.html file for now. This website will serv ...

Zone.js error: Promise rejection caught

When I call a function from an external library on page load in my Angular application, Chrome dev tools console shows the error message: "Unhandled Promise rejection: Cannot read properties of undefined (reading 'page') ' Zone: <root> ...