How to get element by name in HTML – getElementsByName
The getElementsByName() method is use to get the element by name. However be aware of the getElementsByName() method always return an array as output.
<html>
<head>
<script type="text/javascript">
function showElements(){
alert(document.getElementsByName("myInput")[0].value);
}
</script>
</head>
<body>
<form >
<input name="myInput" type="text" value='testing'><br>
<br>
<input name="submit" type="button" onclick="showElements()"
value="Show Me Output">
</form>
</body>
</html>Caution
The method always return an array, and we have to use [] to access the value.
For example
alert(document.getElementsByName("myInput").value);It will prompt out an undefined value
alert(document.getElementsByName("myInput")[0].value);It will prompt out an expected ‘testing’ value
One more time, there are no getElementByName() exists, it is getElementsByName(), with a ‘s’ ![]()
But there is getElementById, which returns 1 element, because ID is supposed to be unique to each element. If not, the first occurence is returned.
getElementById
(without s, case-sensitive = not ID or id)
thanks a lot for this code ,it solved my problem
Thanks, this helped alot
wc, good to know this is helpful.