我想添加几个输入字段(姓名、年龄、位置、状态等...) 到我的表格。
当我点击 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/