简体   繁体   English

TypeError:document.getElementById(…)在javascript中为null

[英]TypeError: document.getElementById(…) is null in javascript

This is my coding for dynamic field validation. 这是我用于动态字段验证的编码。 if i use this function i got 'TypeError: document.getElementById(...) is null' this kind of error. 如果我使用此功能,则会收到“ TypeError:document.getElementById(...)为null”这种错误。

function sr_answer_val(){
  var cnt=parseInt(document.getElementById("add_field_cnt").value);
  var submitAllow=true;
  for(var i=1;i<cnt;i++){
    if(document.getElementById("cust_field_"+i).value ==''){
      alert('Answer Should be Mandatory');
      submitAllow=false;
      return false;     
    }
  }
}

There's for sure no element with id named "add_field_cnt" in your html. 您的html中肯定没有ID为“ add_field_cnt”的元素。 Check if there's no any typo. 检查是否有错字。

Your element add_field_cnt is (DOM) not loaded/created. 您的元素add_field_cnt未(DOM)加载/创建。

I guess you're loading the js in head, instead do it at the bottom of body or use document.ready 我想你是在头上加载js,而是在body的底部或使用document.ready

The element with id passed to getElementById() does not exist. id传递给getElementById()的元素不存在。 So, you can do a null check 因此,您可以进行空检查

var elem = document.getElementById("add_field_cnt");
if(typeof elem !== 'undefined' && elem !== null) {
    var cnt = parseInt(document.getElementById(elem).value);
    .......// do your stuff
}

There is no element with the ID add_field_cnt so you are getting this error 没有ID为add_field_cnt的元素,因此出现此错误

var cnt=parseInt(document.getElementById("add_field_cnt").value);

please check your element is Created or not with add_field_cnt ID. 请使用add_field_cnt ID检查您的元素是否已创建。

i hope so. 希望如此。

Probably your custom fields are not all defined, so when you try to acces one of them it is undefined. 您的自定义字段可能未全部定义,因此当您尝试访问其中一个时,它是未定义的。

Check the existence of the element before accesing it like: 在访问元素之前检查元素的存在,例如:

function sr_answer_val() {
    var cnt = parseInt(document.getElementById("add_field_cnt").value);
    var submitAllow = true;
    for (var i = 1; i < cnt; i++) {
        if (document.getElementById("cust_field_" + i) && document.getElementById("cust_field_" + i).value == '') {
            alert('Answer Should be Mandatory');
            submitAllow = false;
            return false;
        }
    }
}

Demo: http://jsfiddle.net/IrvinDominin/X3ZnQ/ 演示: http//jsfiddle.net/IrvinDominin/X3ZnQ/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM