繁体   English   中英

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

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

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

当我单击“ 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属性。

form添加id属性

 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM