javascript - 如何找到表单中的所有输入字段并使用 Javascript 将它们的值复制到 textarea 中?

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

最佳答案

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

关于javascript - 如何找到表单中的所有输入字段并使用 Javascript 将它们的值复制到 textarea 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28781969/

相关文章:

javascript - 为什么对匿名函数的引用继续存在?

javascript - Tween.js |即使我循环播放,我的补间也不会更新

javascript - 循环遍历对象的嵌套数组

javascript - 更新后点击功能不再有效

javascript - md-select 不更新 ng-value 文本

php - 通过 PHP 将选择表单发送到电子邮件

javascript - iron-page 上的 iron-scroll-threshold

forms - 通过 html 表单发送带有特定键的 map

javascript - 为什么我的 ajax、javascript 不起作用?

javascript - ReactJS:访问子方法