简体   繁体   中英

property undefined but console.log can see it

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM