Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find all input fields inside a form and copy their values into textarea using Javascript?

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>
like image 235
user2910182 Avatar asked Dec 13 '25 16:12

user2910182


1 Answers

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>
like image 98
Artur Filipiak Avatar answered Dec 15 '25 05:12

Artur Filipiak