23
votes

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);
}
2
Can you please attach the relevant part of your HTML? - Eran Zimmerman Gonen
Are you sure WallSearch is the ID of the input element? If it was, you would not get that error: jsfiddle.net/fkling/x9Vf2 - Felix Kling
How do you check for DOM readiness? - bjornd
i've added the code i used to check for DOM readiness and i am sure that the id is "WallSearch". The function is getting called but it errors out - Praveen
The error means that what ever element is returned by getElementById('WallSearch'), it does not have a value property. Every form field has a value property, hence it seems it does not return the right element. Please post your HTML or create a jsfiddle.net demo. - Felix Kling

2 Answers

14
votes

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.

8
votes

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);
}