如何找到表单中的所有输入字段,并使用Javascript将它们的值复制到文本区域

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

本文关键字:Javascript 文本 复制 区域 表单 何找 字段 输入      更新时间:2023-09-26

我想在表单中添加几个输入字段(名称年龄位置状态等)。

当我单击submit按钮时,如何获取表单中的所有值,并将它们放置在单个文本区域元素中,以便轻松复制?谢谢你的帮助!

我当前的代码:

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

在这种特殊情况下,不要使用输入字段的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>

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

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