Click here to Skip to main content
15,897,891 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:

<html>
<head>
<title>Test</title>
<script type="text/javascript">
function fun(){
		var list = document.getElementsByName("array");
		document.write(list[0].value+"<br>");
		document.write(list[1].value+"<br>");
		document.write(list[2].value+"<br>");
		
}
</script>
</head>
<body>
<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()">
</body>
</html>


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
Posted
Updated 4-Aug-17 6:12am

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 document.open, 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:
JavaScript
function fun(){
    var list = document.getElementsByName("array");
    
    var values = [];
    for (var i = 0; i < list.length; i++){
        values.push(list[i].value);
    }
    
    document.write(values.join("<br />"));
    document.close();
}
 
Share this answer
 
Here is the working Plunker. When you use document.write , it will overwrite the previous value.


Working Plunker
[^]

Hepe this helps
 
Share this answer
 

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