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

Leveraging JavaScript variables within a jQuery selector

My <form> includes the following input... Term ID: <input type="text" name="data_array[0][term_id]" size="5" value="' . $highest_term_id . '"> with the $highest_term_id being set by PHP. I am attempting to increment the "data_array ...

What is the correct way to align an InputLabel in Material UI?

https://i.stack.imgur.com/Uafr1.png Looking for advice on styling the InputLabel in my code to improve its appearance. Code snippet below: <FormControl fullWidth> <InputLabel >Select EPE</InputLabel> <Select ...

Challenges with jQuery Image Sliders

Currently, I am learning from a tutorial on creating a custom jQuery content slider and you can find the tutorial here. Everything is working smoothly in terms of creating the image slider. However, I am facing an issue where I want to have the 'Next ...

Trigger a modal to open based on a specific condition

I have successfully implemented a default modal from Materialize, but now I am looking to add a conditional opening feature to it. In my application, there is a countdown timer and I want the modal to automatically appear when the countdown reaches a certa ...

What is the correct way to use getServerSideProps?

Lately, I've been exploring the world of web development by creating a web app using NextJS. While I have some knowledge of the basics in this field, I found myself a bit lost when working with NextJS since I hadn't worked with React before. One ...

Ways to ensure that a URL is distinct once a link has been clicked

On my website list.php, I have a code snippet that changes the video in an iframe when a link is clicked. However, the URL remains as list.php instead of changing to something like list.php/Anohana10. How can I update the URL to reflect the selected video? ...

Exploring the power of Next.js dynamic routes connected to a Firestore collection

Currently seeking a solution to create a dynamic route that will display each document in a Firestore collection using Server-side Rendering. For instance, if there is a document named foo, it would be accessible at test.com/foo under the [doc] page compo ...

Is there a way for me to retrieve the UrlMatcher from ui-router?

While exploring the ui-router documentation, I came across an object called UrlMatcher. This object contains useful methods like exec, but I am struggling to find clear instructions on how to access it. Nevertheless, the documentation page provides a detai ...

The password prompt window refuses to align with the center of the screen. This

I've been struggling to position the Javascript popup notification using the width, height, top, and left parameters in the window.open function. No matter what I attempt, it stubbornly remains in the top-left corner. Can someone offer some guidance o ...

The retrieval of data from AWS Dynamodb in Node.js is not done synchronously

I recently started working with Node.js and DynamoDB. I created a Node.js SDK to retrieve a single row from a DynamoDB table. The data is being fetched correctly, but there is a delay which is causing an error. Below is a snippet of my code: var AWS = re ...

Add the slide number and total count in between the navigation arrows of the owl carousel

In my Angular application, I am utilizing an ngx owl carousel with specific configurations set up as follows: const carouselOptions = { items: 1, dots: false, nav: true, navText: ['<div class='nav-btn prev-slide'></div>' ...

What is the best way to clear cookies when making external API calls in Next.js?

Despite my efforts, I have been unable to successfully remove cookies from my API calls in NextJS using Axios as the httpClient. The accumulation of cookies in users' browsers is causing issues and bloating, but I can't seem to find a solution. ...

Send an AJAX request to the server without waiting for a response using a JavaScript variable

My click counter is not sending variables to the server. I have tried finding examples on how to do this, but no matter what I attempt, the data is not being sent to the server. It seems like using AJAX would be the best option, but I must be doing someth ...

Executing Javascript on Selenium RC with PHP is a crucial skill to have in your toolkit

Is there a way to execute Javascript from Selenium RC? I have been trying different methods with no success so far. I attempted the following approach: I created a custom function in user-extensions.js: function sayhello() { document.write('hel ...

Executing a javascript function numerous times

Here are a few examples: <div class="statement">text goes here</div> <div class="response"><input type="text" id="amount1" style="border: 0; color: #f6931f; font-weight: bold;" /></div> <div id="sli ...

Capturing C# log data for JavaScript interactions

Can anyone provide recommendations on how to capture JavaScript interactions in a browser using C#? I am interested in developing a web crawler that can track these interactions, allowing me to search for potentially harmful calls. ...

Using AngularJS API within a standalone function: Tips and tricks

I'm diving into the world of AngularJS and I want to make an HTTP GET request to a distant server without messing up my current view code. After some research, I discovered a way to execute a function right after the HTML is loaded by using a standalo ...

You can't retrieve a JSON object using Javascript

Every time I execute the javascript/php code below, I encounter an issue where I keep receiving "undefined" when trying to alert the 'userid' property of the json object. However, if I turn the json object into a string using stringify(), it corr ...

.toggle function malfunctioning

Upon page load, I have a script that toggles the County menu. The goal is to hide the county menu if any country other than "United Kingdom" is selected on page load. If the user selects another country after the page has loaded, there is an issue where ...

What is the method for retrieving an array or object that contains a collection of files designated for uploading within the jQuery file upload plugin?

Currently, I have successfully integrated a form into my Rails site and set up the jQuery file upload plugin. The upload form functions properly with the ability to select multiple files and utilize all ajax upload features. However, a challenge I am faci ...