[英]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.