user1419810 user1419810 - 1 year ago 85
Javascript Question

Multiple Event Listners

I have a user generated table that contains a quantity input field in every row that, when it changes, I'd like to trigger a further calculation. The table can have multiple rows and therefore also multiple instances of the quantity field.

The following snippet listens for a change in "qty" however this only seems to work for the first row of the table. Does anyone know how I can make the event listener apply to all instances of the "qty" field.

// On Quantity Change:
var qtys = document.getElementsByName("qty[]");
var i;
for (i = 0; i < qtys.length; ++i) {
qtys[i].addEventListener("change", totalIt, false);
qtys[i].addEventListener("input", totalIt, false);

Here is a jsfiddle of the code...

Answer Source

Looks like the other table rows are added dynamically - instead of adding event listener to them you can add it on the parent table and check the target element's name, or you can bind the event to each row that you are adding dynamically.

example for option 1 -

var table = document.getElementById('dataTable');
dataTable.addEventListener('change', function(e){
   if ("name") === 'qty[]') {

dataTable.addEventListener('input', function(e){
   if ("name") === 'qty[]') {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download