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

用户名

这是我用于动态字段验证的编码。如果我使用此功能,则会收到“ 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;     
    }
  }
}
欧文·多米宁(Irvin Dominin)

您的自定义字段可能未全部定义,因此当您尝试访问其中一个时,它是未定义的。

在访问元素之前检查元素的存在,例如:

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Ajax Uncaught TypeError: document.getElementById(...) is null

TypeError:document.getElementById(...)为null不会停止出现

在异常TypeError上暂停:document.getElementById(...)为null

我找不到错误?TypeError:document.getElementById(...)为null

Javascript document.getElementById

TypeError:使用JSP的getElementById为null

document.getElementById() 为空

Javascript:TypeError:document.getElementById(...)为空动态创建的<div> MVC4

Javascript Document.getElementById返回null

document.getElementById()返回null

document.getElementById返回null

javascript document.getElementById 循环

Javascript document.getElementById调试

JavaScript document.getElementById问题

数组中的document.getElementById

document.getElementById()。value卡在javascript中

如何将 document.getElementById(...) is null 设置为 true

离子2 document.getElementById返回null

document.getElementById 始终返回 null

所有 document.getElementById('') 返回 null

document.getelementbyid在循环中返回null

从document.getElementById()。value获取null

JavaScript:$('foo')与document.getElementById('foo')

简化 JavaScript 代码。document.getElementById

如何使用Javascript“ document.getelementbyid”

document.getElementById仅在Firefox中工作

在const变量中存储document.getElementById()

如何访问从jQuery中的document.getelementbyId()获得的JavaScript对象?

JavaScript 中的代码含义“document.getElementById('msg').innerHTML