Connecting Tech Pros Worldwide Forums | Help | Site Map

how to get element's Id or name for dynamically created element(textbox)

Newbie
 
Join Date: Aug 2008
Posts: 1
#1: Aug 29 '08
Hi all,

I have created some textboxes dynamically by using

var sun = document.createElement('input'); with button click.

after some time I will re visit the fields, how do I retrive that element's Id or name onblur event.

Bythe following code I used to get the value of the specified element, but I want id or name of that element .

Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <script language="javascript">
  4. function init(){
  5. newFieldElement = document.createElement( 'INPUT' );
  6. newFieldElement.onblur = show;
  7. document.body.appendChild(newFieldElement);
  8.  
  9. newFieldElement1 = document.createElement( 'INPUT' );
  10. newFieldElement1.onblur = show;
  11. document.body.appendChild(newFieldElement1);
  12. }
  13. function show(){
  14. alert( this.value );
  15. }
  16. </script>
  17. </head>
  18. <body onload="init()">
  19. </body>
  20. </html>
  21.  
code examples are highly appreciated.

Thanks & regards,
zimbu

Dormilich's Avatar
Moderator
 
Join Date: Aug 2008
Location: Leipzig, Germany
Posts: 3,662
#2: Aug 29 '08

re: how to get element's Id or name for dynamically created element(textbox)


Before you can retrieve an id or name you have to set them (while creation). Otherwise, how should the browser know which value to assign?
if id and name are set you can access them with (in case of the 1st input field)
Expand|Select|Wrap|Line Numbers
  1. document.getElementsByTagName("input")[0].id // and
  2. document.getElementsByTagName("input")[0].name
Ferris's Avatar
Member
 
Join Date: Oct 2007
Location: Shanghai
Posts: 102
#3: Aug 30 '08

re: how to get element's Id or name for dynamically created element(textbox)


Hi,you should set id and name when creating them. If you didn't set id,it will be null.

I write an example for you.

Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <head>
  3. <script language="javascript">
  4. function init()
  5. {
  6.     //element with NO id
  7.     newFieldElementNoId = document.createElement( 'INPUT' );
  8.     newFieldElementNoId.onblur = show;
  9.     document.body.appendChild(newFieldElementNoId);
  10.  
  11.     //element with id
  12.     var i;
  13.     for ( i=0;i<5;i++)
  14.     {
  15.         newFieldElement = document.createElement( 'INPUT' );
  16.         newFieldElement.setAttribute('id','myfieldid'+i);
  17.         newFieldElement.setAttribute('name','myfieldname'+i);
  18.         newFieldElement.onblur = show;
  19.         document.body.appendChild(newFieldElement);
  20.     }
  21. }
  22. function show(){
  23.  
  24.     alert( 'id=' + this.getAttribute('id') + "\n" +  'name=' + this.getAttribute('name') + "\n" + "value=" + this.value );
  25. }
  26. </script>
  27. </head>
  28. <body onload="init()">
  29. </body>
  30. </html>
  31.  
Reply