Reputation: 23
I am creating a dynamic form which consists of sku, qty and subtotal. So the form starts out from no inputs and filled up as the user searches for products. Upon keypress I need to compute the total quantity and show it to the user via javascript.
I am using getting all quantity input elements via getElementsByClassName upon keypress and counting all values. however the browser is returning an error (Uncaught TypeError: Cannot read property 'value' of undefined) but I can log the value.
I only use native JavaScript no jQuery.
qtyelements = document.getElementsByClassName('qty-element');
var x;
var count = 0;
for(x = 0; x <= qtyelements.length; x++){
console.log(qtyelements[x].value);
count = count + parseInt(qtyelements[x].value);
}
Here is an image of my problem
Upvotes: 0
Views: 144
Reputation: 208002
Length gives you the number of items, but the collection is zero based. So for example while the length may be three, you only loop to two (0, 1, 2).
So change:
x <= qtyelements.length
to:
x < qtyelements.length
In your case it looks like you only have two elements, so the indices would be 0 and 1, but you check to see if 2 exists with the <=
, hence the undefined.
Upvotes: 2