javascript getElementById function not working

361 Views Asked by At

I tried the following: it is working fine

function saveTitle(index,id){
   arrtitle[1] = document.getElementById("title_1").value;
   arrtitle[2] = document.getElementById("title_2").value;
   arrtitle[3] = document.getElementById("title_3").value;
}

but as I tried the following:

function saveTitle(index,id){
   for(i=1;i<=count;i++)
   arrtitle[i] = document.getElementById("title_"+i).value;
}

It gives me an error that : Uncaught TypeError: Cannot read property 'value' of null

Please suggest me something. Thanks...

2

There are 2 best solutions below

0
Vladu Ionut On BEST ANSWER

You can use querySelectorAll to get all the elements that contains "title_" string . See the bellow code.

function getTitles() {
  var arrtitle = [];
  var elements = document.querySelectorAll("*[id*='title_']");

  for (i = 0; i < elements.length; i++) {
    var titleId = elements[i].id.replace("title_", "");
    arrtitle[titleId] = elements[i].value;
  }
  return arrtitle;
}
getTitles();
0
Joe Enos On

Based on what you've posted, if that's your actual code, the only possibility seems to be that count is higher than the maximum element that exists (or there's a hole). For example, count might be 4, and there is no element with the id of title_4.

The javascript debugger would help you find this pretty easily.

I'd also suggest using braces around the body of your for loop, which would significantly help readability.