admin管理员组

文章数量:1278691

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

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);
}
Share Improve this question edited Dec 20, 2013 at 14:59 Marc Gravell 1.1m273 gold badges2.6k silver badges3k bronze badges asked Dec 20, 2013 at 13:28 SivadineshSivadinesh 1572 gold badges5 silver badges15 bronze badges 3
  • 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 Commented Dec 20, 2013 at 13:32
  • JSLint or JSHint are your friends. Hook them up to your IDE – epascarello Commented Dec 20, 2013 at 13:34
  • for this mistake you developper console, give you a 'no existing method "..." ' – kevpoccs Commented Dec 20, 2013 at 13:35
Add a ment  | 

3 Answers 3

Reset to default 9

you forgot the global name document for use getElementById

document.getElementById('idkey'+j)

You're missing document before getElementById:

for(j=0; j<lines.length; j++){
    var lblElementID = document.getElementById('idkey'+j);
    console.log(lblElementID);
}

You forget to use the document global namespace

The correct way to access the getElementById is the following

document.getElementById('idkey')

本文标签: javascriptdynamically added text idgetElementByIdStack Overflow