Cannot read property length of undefined

295,893

Solution 1

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

Solution 2

perhaps, you can first determine if the DOM does really exists,

function walkmydog() {
    //when the user starts entering
    var dom = document.getElementById('WallSearch');
    if(dom == null){
        alert('sorry, WallSearch DOM cannot be found');
        return false;    
    }

    if(dom.value.length == 0){
        alert("nothing");
    }
}

if (document.addEventListener){
    document.addEventListener("DOMContentLoaded", walkmydog, false);
}
Share:
295,893
Praveen
Author by

Praveen

I am doing my M.S in Electrical and Computer Engineering at Carnegie Mellon University. I like to build good, immersive products and assist users with the help of technology.

Updated on August 11, 2021

Comments

  • Praveen
    Praveen over 2 years

    I am trying to simply check if I have an empty input text box but I get this error when I run this in Chrome:

    Uncaught TypeError: Cannot read property 'length' of undefined.

    Here is how I go about doing it. I check for DOM readiness and then call the function:

    function walkmydog() {
        //when the user starts entering                                                                                                                                                
        if(document.getElementById('WallSearch').value.length == 0) {
            alert("nothing");
        }
    }
    
    if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", walkmydog, false);
    }