Uncaught TypeError: Cannot call method 'toString' of null

Toni Cesar A. Amaral picture Toni Cesar A. Amaral · Dec 20, 2012 · Viewed 13.6k times · Source

I'm trying to create a class in JavaScript to validate a form. That'll check the form elements and validate a field if it has a specific attribute.

However, the call to getAttribute isn't returning a value. It doesn't get the value inside another variable, but, if I print, it works well.

Here's the code for my class:

function valida() {
    document.getElementById("msgDiv").innerHTML="";
    var totalErros=0; 
    var x=document.getElementById("frm1");
    for (var i=0;i<x.length;i++){
        var input=document.getElementsByTagName("input")[i];
        var campo=input.getAttribute("id");
        var tipo=input.getAttribute("tipo");
        var nome=input.getAttribute("nome");
        var id=campo.toString(); //the error goes here
        //var valor=_$(id).value;
        alert(campo);

        switch (tipo) {
            case "obrigatorio":
                if(document.getElementById(id).value==""){
                    document.getElementById("msgDiv").innerHTML+="Deu erro no campo "+nome+"<br />"; 
                    totalErros++;}
                    break
            case "oemail":
                if(document.getElementById(id).value==""){
                    document.getElementById("msgDiv").innerHTML+="Deu erro no campo "+nome+"<br />"; 
                    totalErros++;}
                    break
            case "email":
                if(!ValidaEmail(document.getElementById(id).value)){
                    document.getElementById("msgDiv").innerHTML+="O "+nome+" que você informou é inválido "+document.getElementById(id).value+"  <br />"; 
                    totalErros++;}
                    break
            default:
                document.getElementById("msgDiv").innerHTML+="<br />";
        }            
    }
    if(totalErros==0) {  
        document.getElementById("msgDiv").innerHTML="Agora foi "+ totalErros;
        return true;
    }
}

Answer

Levi Botelho picture Levi Botelho · Dec 20, 2012

Your problem is this:

var input=document.getElementsByTagName("input")[i];
var campo=input.getAttribute("id");
//...
var id=campo.toString(); //the error goes here

You are getting a given input element and storing it in the variable input. You are then getting the ID of that element and storing it in the variable campo. You then take campo and call toString() on it.

The problem is that at least one input element does not have an ID. Because you cannot call toString on null, you get an error.

You don't actually need to call toString() in the first place. Simply use campo as is. It will either be null (if there is no ID) or a string.