最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught TypeError: Cannot call method 'toString' of null - Stack Overflow

programmeradmin4浏览0评论

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

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;
    }
}
Share Improve this question edited Sep 6, 2013 at 9:16 Apurva Mayank 7472 gold badges12 silver badges33 bronze badges asked Dec 20, 2012 at 13:18 Toni Cesar A. AmaralToni Cesar A. Amaral 391 gold badge2 silver badges4 bronze badges 2
  • 1 Your English is good enough, Toni! – DOK Commented Dec 20, 2012 at 13:30
  • Doing var input=document.getElementsByTagName("input") over and over again in the for loop is bad for performance. – epascarello Commented Dec 20, 2012 at 13:57
Add a ment  | 

2 Answers 2

Reset to default 2

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.

This part of your code piqued my curiosity:

var x=document.getElementById("frm1");
for (var i=0;i<x.length;i++){
    var input=document.getElementsByTagName("input")[i];

This takes the collection of all <input> elements on your page and takes the ith one each time; and who knows what input element you may get.

If you just want to traverse only the elements of the form you're interested in, this is much easier and faster:

var x = document.getElementById('frm1'),
input,
campo;

for (var i = 0, n = x.length; i != n; ++i) {
    input = x.elements[i];
    if (campo = input.id) {
        // rest of your code
    }
}

As you can see, I take the id property instead of the id attribute; this is generally a better thing to do, because changes in properties may not always be reflected in the respective attribute.

Also, the .toString() is superfluous, it's already a string if not null.

Update

As @bfavaretto pointed out in the ment section, this part of your code could also be simplified:

if(document.getElementById(id).value==""){    

to this:

if (input.value == '') {

That would work whether the input element has an id or not

发布评论

评论列表(0)

  1. 暂无评论