1
<!DOCTYPE html>
<html>
<head>
<script>
function getElements()
{
  var v = document.getElementById('view');
  var x=document.getElementsByTagName("input");
  for(var i=0; i<x.length; i++){
  v.innerHTML = x[i].value+"<br>";
  }  
}
</script>
</head>
<body>

<input type="text" size="20"><br>
<input type="text" size="20"><br>
<input type="text" size="20"><br><br>
<input type="button" onclick="getElements()" value="How many input elements?">

<p id='view'></p>
</body>
</html>

This is my code where I want to fetch the values of the fields and iterate them below in the "p" tag but it kept showing me the value of the last input which is the submit value.

The nature of the program was for me to fetch data from many inputs elements including file, upload field and submit them to the server script.

2 Answers 2

1

You need to change your html and javascript as following which will not give you button's value(which is not needed) :

HTML:

<input type="text" size="20"><br>
<input type="text" size="20"><br>
<input type="text" size="20"><br><br>
    <button onclick="getElements()" value="How many input elements?" >How many input elements?</button>
<p id='view'></p>

JS:

function getElements()
{
  var v = document.getElementById('view');
    v.innerHTML = "";
  var x=document.getElementsByTagName("input");
  for(var i=0; i<x.length; i++){
      v.innerHTML += x[i].value+"<br>";
  }  
}

DEMO : http://jsfiddle.net/f7bLq0b4/

Sign up to request clarification or add additional context in comments.

1 Comment

please accept the answer if you have got the solution :)
0

Make the below change in your code to make it work.

<!DOCTYPE html>
<html>
<head>
<script>
function getElements()
{
  var v = document.getElementById('view');
  var x=document.getElementsByTagName("input");
  for(var i=0; i<x.length; i++){
  v.innerHTML += x[i].value+"<br>";
  }  
}
</script>
</head>
<body>

<input type="text" size="20"><br>
<input type="text" size="20"><br>
<input type="text" size="20"><br><br>
<button  onclick="getElements()">How many input elements?</button>

<p id='view'></p>
</body>
</html>

To append a string you need to use +=.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.