如何在表单中找到所有输入字段并使用Javascript将其值复制到textarea?

时间:2015-02-28 12:59:20

标签: javascript html forms

我想添加几个输入字段(名称年龄位置状态等) ......)到我的表格。

当我点击submit按钮时,如何获取表单中的所有值并将它们放入单个textarea元素中,以便于复制?谢谢你的帮助!

我目前的代码:

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

2 个答案:

答案 0 :(得分:2)

在特定情况下,请勿使用输入字段的id属性。

id

中添加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>

答案 1 :(得分:0)

您可以在段落中显示文本数据,然后可以轻松选择:

<!DOCTYPE html>
<html>
<body> 

<h1>My Web Page</h1>

<p id="demo">A Paragraph</p>
<form>
    <input type="text" name="in01" id="txt1">
    <input type="text" name="in02" id="txt2">
    <button type="button" onclick="ShowText();">Submit</button>
</form>

<span id="show"></span>
<script>
    function ShowText(){
        var txt = document.getElementById('txt1').value;
        var show = document.getElementById('txt1').value;
        //window.alert(txt);
         document.getElementById("demo").innerHTML = txt +" "+show;
    }
</script>
</body>
</html>