Click here to Skip to main content
15,068,678 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am a beginner in javascript. I was trying to write a code that takes input from the user in textboxes . I wanted to capture the inputs in an array, so i looked up for a method on the internet. I got a method document.getElementsByName("name") that returns an HTML collection of all element with that name. I wrote a script to utilise that function, but strangely, it is just printing only the first value in the list. The length function shows me the correct length, i.e 3 , but only the first value is being printed. Any help would be appreciated. Here is the code:

<script type="text/javascript">
function fun(){
		var list = document.getElementsByName("array");
<input type="text" name="array"><br>
<input type="text" name="array"><br>
<input type="text" name="array"><br>
<input type="button" value="go" onclick="fun()">

What I have tried:

I have tried printing the length, as well as individual elements of the list one by one. All of them works. But when i want to print all of the values at once, it just prints the first value
Updated 4-Aug-17 6:12am

Here is the working Plunker. When you use document.write , it will overwrite the previous value.

Working Plunker

Hepe this helps
Check out the error console in your browser, and you'll see the problem:
TypeError: list[1] is undefined

As soon as you use document.write, the entire contents of the document are replaced with whatever you've written.
Note: as document.write writes to the document stream, calling document.write on a closed (loaded) document automatically calls, which will clear the document.

Clearing the document destroys the elements on it, so you can no longer read the value of the inputs.

You'll need to read the values before writing to the document:
function fun(){
    var list = document.getElementsByName("array");
    var values = [];
    for (var i = 0; i < list.length; i++){
    document.write(values.join("<br />"));

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900