使用javascript在按钮单击上添加文本框 [英] Adding textbox on button click with javascript

查看:109
本文介绍了使用javascript在按钮单击上添加文本框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个带有用于宠物的文本框和一个添加宠物"按钮的Web表单.每次单击该按钮时,应在原始文本框下方显示一个附加文本框.

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.

我假设这将通过onclick事件来完成,但是我不知道如何使它工作.

I'm assuming this would be accomplished with an onclick event, but I can't figure out how to get it to work.

这是我到目前为止的代码:

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.

更新: 在阅读答案后,我意识到我应该包含更多的代码,以便让大家更好地了解页面的实际布局.我的表单中有几个文本字段,需要其他文本框显示在原始宠物"文本框的正下方.这是我凑在一起的小提琴,目的是让大家对布局有个更好的了解. http://jsfiddle.net/a5m8nqwk/

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/

推荐答案

您可以轻松地将元素添加到DOM:

You could easily add elements to the 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());
});

这篇关于使用javascript在按钮单击上添加文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆