-1

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... http://jsfiddle.net/jDfFU/95/

user1419810
  • 836
  • 1
  • 16
  • 29
  • You didn't put the html side of it. So I guess it is because you did name just the first row. – Hirad Nikoo Sep 11 '16 at 13:46
  • 1
    Another possibility is that this code runs before the entire table is generated. No way to know for sure without seeing a [complete example](http://stackoverflow.com/help/mcve). – JJJ Sep 11 '16 at 13:48
  • Give us some html code too. – Paweł Mikołajczyk Sep 11 '16 at 13:53
  • 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 is the e.target.name == 'qty[]' check the following example http://stackoverflow.com/a/39433396/4819077 – naortor Sep 11 '16 at 14:08
  • Isnt that a jquery solution? Is there no way to do this with pure javascript? – user1419810 Sep 11 '16 at 14:10
  • Of course there is. jQuery *is* JavaScript so if it's possible with jQuery then it's possible without it too. Like I suspected, in the jsfiddle you never call the function `totalIt` so it never runs. The only code that adds the handlers is a separate `window.onload` event on line 75 that adds them only to the first row. – JJJ Sep 11 '16 at 14:27
  • Not true Juhana, I do call totalIt a number of times and the onload function is for price calculations, not the total calculations – user1419810 Sep 11 '16 at 14:50

1 Answers1

1

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 (e.target.getAttribute("name") === 'qty[]') {
        totalIt();
    }
});

dataTable.addEventListener('input', function(e){
   if (e.target.getAttribute("name") === 'qty[]') {
        totalIt();
    }
})
naortor
  • 2,019
  • 12
  • 26
  • Cool, thanks although if I use this it seems to break the code, i.e. cant add rows any more, any idea what might be going wrong? – user1419810 Sep 11 '16 at 14:20