Uncaught TypeError: Cannot read property 'value' of undefined

Discussion in 'JavaScript' started by greatlogix, Sep 11, 2013.

  1. #1
    function deleterow(id){
        document.form1.elements['del[]'][id].value = 1
        count_del_price()
        document.getElementById("tr"+id).style.display = 'none'
    }
    
    function count_del_price(){
        priceminus = 0;
        inputCount = document.form1.elements['del[]'].length //document.form1.elements['tcounter'].value
        for(i=0; i<=inputCount; i++){
            if(document.form1.elements['del[]'][i].value == 1){// Uncaught TypeError: Cannot read property 'value' of undefined 
                priceminus += parseFloat(document.form1.elements['price[]'][i].value) * parseFloat(document.form1.elements['qty[]'][i].value);
            }
        }
    }
    Code (markup):
    I am getting "Uncaught TypeError: Cannot read property 'value' of undefined" error in if statement. if part of the code never executes. What's wrong I am doing here. Please help.
     
    greatlogix, Sep 11, 2013 IP
  2. HuggyStudios

    HuggyStudios Well-Known Member

    Messages:
    724
    Likes Received:
    20
    Best Answers:
    26
    Trophy Points:
    165
    #2
    Can you post the HTML code associated with this script?
     
    HuggyStudios, Sep 12, 2013 IP
  3. Basti

    Basti Active Member

    Messages:
    625
    Likes Received:
    6
    Best Answers:
    3
    Trophy Points:
    90
    #3
    document.form1
    requires that your form has name="form1"

    I suspect that you just have an id="form1" there? In that case either add the name tag or use
    document.getElementById('form1')
     
    Basti, Sep 12, 2013 IP
  4. JoeSimmons

    JoeSimmons Greenhorn

    Messages:
    11
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    21
    #4
    In this line
    for(i=0; i <= inputCount; i++){
    Code (markup):
    I can't say for sure, since I haven't seen your HTML code, but I think the problem is the less-than-or-equal-to comparison operator in that line.
    Try changing that to a less-than comparison operator.
    for(i=0; i < inputCount; i++){
    Code (markup):

    The reason it's doing that is because you're going one higher than what exists on the page.


    --------------------------


    Let me show you an example. Take this code.
    var array = ['a', 'b', 'c'];
    Code (markup):
    It has a length of 3, but it's highest index is 2 because arrays' indexes start at 0.

    So if you were to do this code (similar to what you did)
    for (var i = 0; i <= array.length; i++) {
        alert( array[i] );
    }
    Code (markup):
    The last alert value would be undefined because the loop is allowed to run while 'i' and 'array.length' are the same,
    which means you will be trying to access array[3] which doesn't exist; only 0, 1, and 2 exist.

    Hope that helps.
     
    JoeSimmons, Sep 13, 2013 IP