如何动态添加和删除输入文本框?
假设有一组元素,例如:
<p>What's your question?</p>
<input type='text' name='question'/>
还有一个按钮:
<input type='button' value='Add' />
我想实现当我单击按钮时,将在 html 页面上动态创建元素组。在元素旁边还有一个删除按钮:
<input type='button' value='Remove' />
当我单击它时,元素将被删除。
该流程可以动态执行多次,并且所有这些元素都包含在一个表单中。用户输入答案后,所有信息将发布到另一个页面。
我觉得这个功能可以用js实现,但是不知道怎么实现。请提供一些代码。谢谢!
Suppose there is a group of elements like:
<p>What's your question?</p>
<input type='text' name='question'/>
And there is a button:
<input type='button' value='Add' />
I want to implement that when I click the button, the group the elements will be created on the html page dynamically. Also beside the elements there is a remove button:
<input type='button' value='Remove' />
When I click it, the elements will be removed.
The process can be executed multiple times dynamically, and all these elements are contained in a form. After user input the answer, all information will be posted to another page.
I think this function can be implemented by js, but I don't know how to do it. Please provide some code. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的方法是使用 jQuery 并在按钮上执行添加/删除操作,单击
HTML:
JavaScript:
Fiddle: http ://jsfiddle.net/XZqPa/
The easiest way to do this is to use jQuery and do the add / remove operations on the button click
HTML:
JavaScript:
Fiddle: http://jsfiddle.net/XZqPa/
这个问题已经被问过很多次了。搜索“Javascript 显示隐藏元素”。
就我个人而言,我会使用 jQuery 库,使用 ID 标记来标记输入元素或围绕您希望动态显示和隐藏的标记的某些 div,并使用以下代码
来隐藏和显示您的标记。此解决方案假设输入元素已在页面中,JaredPar 的解决方案会动态创建您的输入元素。两者都一样好 - 但 jQuery 使这变得非常容易。
如果您想要一个普通的 js 解决方案 - 通过搜索查看其他答案 - 有几个可供选择。
This question has been asked a number of times. Search for "Javascript show hide element".
Personally, I would use the jQuery library, tag the input element or some div surrounding the markup that you wish to dynamically show and hide, with an ID tag and use code like:
to hide and show your markup. This solution assumes the input element is already in the page, JaredPar's solution dynamically creates your input element. Both are just as good as each other - but jQuery makes this very easy.
If you want a vanilla js solution - see the other answers by searching for them - there are several to choose from.