1

I create text box dynamically and assign its ID dynamically. in javascript if I call getElementById the alert fails, just nothing happens.

<% for(int i=0; i<lines.length;i++) {
  if(lines[i].contains(" ")) { %>
    <input type=text name='key1<%=i%>' id="idkey<%=i%>" value ="<%=abc%>"/>
                          <%
  }
} %>

Javascript :

for(j=0; j<len; j++){
  var lblElement = getElementById("idkey"+j);
  alert(lblElement);
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
Sivadinesh
  • 157
  • 2
  • 5
  • 15
  • First check if elements were properly created in DOM (with FireBug or other developer tools) Also, you say that alert fails - what exactly happens? If element was not found it should show message saying "null" I believe. – lot Dec 20 '13 at 13:32
  • JSLint or JSHint are your friends. Hook them up to your IDE – epascarello Dec 20 '13 at 13:34
  • for this mistake you developper console, give you a 'no existing method "..." ' – kevpoccs Dec 20 '13 at 13:35

3 Answers3

9

you forgot the global name document for use getElementById

document.getElementById('idkey'+j)

kevpoccs
  • 635
  • 5
  • 8
2

You're missing document before getElementById:

for(j=0; j<lines.length; j++){
    var lblElementID = document.getElementById('idkey'+j);
    console.log(lblElementID);
}
Ringo
  • 3,795
  • 3
  • 22
  • 37
1

You forget to use the document global namespace

The correct way to access the getElementById is the following

document.getElementById('idkey')

Igor Šarčević
  • 3,481
  • 1
  • 19
  • 21