Javascript 使用javascript在按钮单击时添加文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26227487/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding textbox on button click with javascript
提问by Sukima
I'm working on a web form with a textbox for pets and an "add pet" button. Each time the button is clicked, an additional textbox should be displayed below the original one.
我正在处理一个带有宠物文本框和“添加宠物”按钮的网络表单。每次单击按钮时,都应在原始文本框下方显示一个附加文本框。
I'm assuming this would be accomplished with an onclick event, but I can't figure out how to get it to work.
我假设这将通过 onclick 事件完成,但我不知道如何让它工作。
Here is the code I have so far:
这是我到目前为止的代码:
<html>
<head>
<title>Project 4</title>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Pets: <input type="text" id="pets">
<input type="button" id="addPet" value="Add Pet">
<br>
</form>
<script type="text/javascript">
function makeCopy() {
var copy = <input type="text">;
return copy;
}
</script>
</body>
</html>
There are other pieces to this as well, but none of them affect this particular problem I am having so didn't see the need to include the full code as it's fairly long.
还有其他部分,但它们都不会影响我遇到的这个特定问题,因此没有看到需要包含完整代码,因为它很长。
Any suggestions are greatly appreciated.
任何建议都非常感谢。
Update: I realize after reading the answers that I should've included more of my code to give you guys a better idea of the actual layout of my page. I have several text fields in my form and need the additional textboxes to be displayed right below the original "pets" textbox. Here's a jfiddle I threw together to give you guys a better idea of the layout. http://jsfiddle.net/a5m8nqwk/
更新:我在阅读答案后意识到我应该包含更多我的代码,以便让你们更好地了解我的页面的实际布局。我的表单中有几个文本字段,需要在原始“宠物”文本框正下方显示其他文本框。这是我拼凑的一个 jfiddle,让你们更好地了解布局。http://jsfiddle.net/a5m8nqwk/
回答by akinuri
Something like this?
像这样的东西?
<form name="myForm" id="myForm" onsubmit="return validateForm()">
Pets: <br />
<input type="text" id="pets" />
<input type="button" id="addPet" value="Add Pet" />
<br/>
</form>
document.getElementById("addPet").onclick = function() {
var form = document.getElementById("myForm");
var input = document.createElement("input");
input.type = "text";
var br = document.createElement("br");
form.appendChild(input);
form.appendChild(br);
}
Edit: I'd suggest using a table to style the input boxes, keep them in line. FIDDLE
编辑:我建议使用表格来设置输入框的样式,使它们保持一致。小提琴
回答by Sukima
You could easily add elements to the DOM:
您可以轻松地向 DOM 添加元素:
function createPetField() {
var input = document.createElement('input');
input.type = 'text';
input.name = 'pet[]';
return input;
}
var form = document.getElementById('myForm');
document.getElementById('addPet').addEventListener('click', function(e) {
form.appendChild(createPetField());
});

