I've created a form with multiple fields and I would like to have a summary of the user entered information show up in a separate area on the page, ( will be hidden div until the submit button is pressed. Once pressed the div will show and hopefully have the input details from the user there)
I have pasted a simplified version of my code (only two input fields).
I am trying to loop through the form fields and then display.
here I have document.write but will be using innerHTML to write to the div.
<!DOCTYPE html>
<html>
<body>
<form id="frm1">
First name: <input type="text" name="fname" value="" ><br>
Last name: <input type="text" name="lname" value="" ><br>
<input type="button" id="btn" onClick="myfun();" value="Submit">
</form>
<p>Return the user input of each element in the form:</p>
<script>
var x = document.getElementById("frm1");
function myfun() {
for ( var i = 0; i < x.length; i++ ) {
document.write(x.elements[i].value);
}
</script>
</body>
</html>
Try:
<script>
var x = document.getElementsByTagName("input");
for(var i = 0; i < x.length; i++)
{
if(x[i].parentNode != document.getElementById("frm1"))
{
x.splice(i, 1);
}
}
for(i = 0; i < x.length; i++)
{
document.getElementById("summarydiv").innerHTML += x[i].value;
}
</script>
That should work, I think. You need to reference all the value properties of the input tags instead of the element itself.
Normally, innerHTML would be bad practice, but it was standardized in HTML5!
Might I suggest working with a library such as jQuery? When you only have this one task to be done in JavaScript, it might not be the optimal solution, but generally it lets you write code much faster, much more readable (and so better to refactor, reuse, etc.) and be cross browser compatible.
$('input#btn').click(function(){
// get all input fields from form with id "frm1" that are of type="text"
// into array $inputs
var $inputs = $('form#frm1 :input[type="text"]'),
result = "";
$inputs.each(function(){
// access the individual input as jQuery object via $(this)
result += $(this).val()+"<br>";
});
// store result in some div
$('div#result').html(result);
});
live demo
This would do what you want and the good part is: You don't need to specify the onclick=".."
in your HTML. So when you want to edit your code in the future, you have only one place to look: the JavaScript code (and not JS parts spread all over the HTML).
You can look up the jQuery methods either on jqapi.com or in the official API documentation.