Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using document.getElementsByName() isn't working?

Tags:

javascript

The code for the second alert command works as intended (displaying the value of the element "to", but the first alert command does not work (it's supposed to do the same thing). 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>
like image 656
user1146930 Avatar asked Jan 13 '12 04:01

user1146930


People also ask

How do you get getElementsByName value?

JavaScript getElementsByName() example How it works: First, select the submit button by its id btnRate using the getElementById() method. Second, listen to the click event of the submit button. Third, get all the radio buttons using the getElementsByName() and show the selected value in the output element.

What is the getElementsByName () method commonly used to obtain?

The getElementsByName() method of the Document object returns a NodeList Collection of elements with a given name attribute in the document.

What is difference between getElementById and getElementsByName?

The difference is that GetElementByID() will retrieve a single element object based on the unique id specified, whereas GetElementsByTagName() will retrieve an array of all element objects with the specified tag name. Then you can obtain the value using GetElementById from your C++ code.

What is document getElementById value in JavaScript?

HTML DOM Document getElementById() The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.


2 Answers

getElementsByName returns an HTMLCollection. You can access the value of the first item like this:

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

Or like this:

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

More info:

  • https://developer.mozilla.org/en/DOM/HTMLCollection
like image 180
Wayne Avatar answered Oct 10 '22 18:10

Wayne


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

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

document.getElementsByName("to")[0].value
like image 36
James Montagne Avatar answered Oct 10 '22 19:10

James Montagne