0

This is my coding for dynamic field validation. if i use this function i got 'TypeError: document.getElementById(...) is null' this kind of error.

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;     
    }
  }
}
Sirko
  • 65,767
  • 19
  • 135
  • 167
  • Check the HTML, if there are really all elements present (at the time of execution) you want to access. – Sirko Jan 20 '14 at 10:53
  • http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – basilikum Jan 20 '14 at 10:54
  • Please provide your HTML markup too. Check if the element __add_field_cnt__ and __cust_field___ exist in yur page – Irvin Dominin Jan 20 '14 at 10:57

5 Answers5

0

There's for sure no element with id named "add_field_cnt" in your html. Check if there's no any typo.

lukaleli
  • 2,867
  • 3
  • 18
  • 31
0

Your element add_field_cnt is (DOM) not loaded/created.

I guess you're loading the js in head, instead do it at the bottom of body or use document.ready

Community
  • 1
  • 1
Praveen
  • 50,562
  • 29
  • 125
  • 152
0

The element with id passed to getElementById() does not exist. 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
}
Linga
  • 9,691
  • 9
  • 45
  • 91
0

There is no element with the ID add_field_cnt so you are getting this error

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

please check your element is Created or not with add_field_cnt ID.

i hope so.

Govinda Rajbhar
  • 2,778
  • 3
  • 32
  • 58
0

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/

Irvin Dominin
  • 29,799
  • 9
  • 75
  • 107