问题描述:

<!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.

网友答案:

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/

网友答案:

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 +=.

相关阅读:
Top