Using document.getElementsByName () not working?

The code for the second alert command works as intended (it displays the value of the item "b", but the first alert command does not work (it should do the same). Why is this?

<html> <head> <script type="text/javascript"> function getValue()   {   alert(document.getElementsByName("to").value); alert(document.forms[0].to.value);    } </script> </head> <body> <form> <input name="to" type="hidden" value="hoolah" /> <input type="button" onclick="getValue()" value="Get Value!" /> <form/> </body> </html> 
+8
javascript
source share
3 answers

getElementsByName returns an HTMLCollection . You can access the value of the first element as follows:

 document.getElementsByName("to").item(0).value 

Or like this:

 document.getElementsByName("to")[0].value 

Additional Information:

+16
source share

getElementsByName returns all elements with the given name. This means that there can be more than one.

If you want to get the value of the first element:

 document.getElementsByName("to")[0].value 
+3
source share

That, since it puts an element in an array, try an example instead:

 function getValues(objName) { var arr = new Array(); arr = document.getElementsByName(objName); alert("total objects with name \"textfield\" = \n" + arr.length); for(var i = 0; i < arr.length; i++) { var obj = document.getElementsByName(objName).item(i); alert(obj.id + " = " + obj.value); } } 
0
source share

All Articles