I want to add a couple of input fields (name, age, location, status, etc...) to my form.
When I click submit button, how do I get all the values inside a form and place them into a single textarea element, so that it's easy to copy? Thanks for the help!
My current code:
<form>
<input type="text" id="txt">
<button type="button" onclick="ShowText();">Submit</button>
</form>
<span id="show"></span>
<script>
function ShowText(){
var txt = document.getElementById('txt');
var show = document.getElementById('show');
show.innerHTML = txt.value;
}
</script>
Don't use id attributes of input fields in that particular case.
Add an id attribute to the form
function ShowText(){
// find each input field inside the 'myForm' form:
var inputs = myForm.getElementsByTagName('input');
// declare 'box' variable (textarea element):
var box = document.getElementById('show');
// clear the 'box':
box.value = '';
// loop through the input elements:
for(var i=0; i<inputs.length; i++){
// append 'name' and 'value' to the 'box':
box.value += inputs[i].name + ': '+inputs[i].value+'\n';
}
}
<form id="myForm">
<input type="text" name="name" placeholder="Name"/><br/>
<input type="text" name="age" placeholder="Age"/><br/>
<input type="text" name="location" placeholder="Location"/><br/>
<input type="text" name="status" placeholder="Status"/><br/>
<button type="button" onclick="ShowText();">Submit</button>
</form>
<p>Show:</p>
<p><textarea cols=30 rows=5 id="show"></textarea></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With