javascript - 将输入添加到 html 表单,使用 javascript

标签 javascript html forms

我有一个 html 表单,我想使用 javascript 添加输入字段。最初我在“正文”下面有自己的输入字段,下面可以添加字段:

            // Create number input field
            var phoneInput = document.createElement("INPUT");
            phoneInput.id = "phone" + instance;
            phoneInput.name = "phone" + instance;
            phoneInput.type = "text";

            // Insert that stuff
            document.body.insertBefore(document.createElement("BR"), element);
            document.body.insertBefore(phoneLabel, element);
            document.body.insertBefore(phoneInput, element);

然后我在 html 文件中的原始输入周围添加了一个“表单”元素。

    <body>
    <form action=searchform.php method=GET>
        <LABEL for="phone1">Cell #: </LABEL>
        <input id="phone1" type="text" name="phone1">
        <input type="button" id="btnAdd" value="New text box" onclick="newTextBox(this);" />
    </form>
    </body>

现在按钮不会添加新的文本框。我的结构不正确吗? 谢谢!

最佳答案

这是因为您将元素附加到正文中,这意味着 insertBefore找不到 element (因为它在 <form> 中,而不是 <body> 中),所以它永远不会被插入。

解决此问题的快速方法是使用 document.body.firstChild.insertBefore .但是,如果表单不再是 body 中的第一个元素,这将不再有效。

更简洁、更好的方法是为您的表单提供一个 ID(例如 <form id="myform"> ),然后使用以下方式访问表单:document.getElementById("myform").insertBefore .然后您可以将表单放在任何地方,并且仍然可以使用 ID 访问它。

关于javascript - 将输入添加到 html 表单,使用 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1951282/

相关文章:

javascript - 带有 Bootstrap 词缀的列跳跃

javascript - 如何将两个不相关的元素粘在一起?

html - 如何将表单选择上的下拉按钮移动到左侧?

php - HTML anchor 导致我的 php $_POST 变量被设置为数组

Javascript 不会改变页面内容

javascript - d3.js:如何遍历备份 DOM

javascript - 对象碰撞条件仅从一侧工作

javascript - 如何使元素假位置 :fixed so it acts fixed until a certain scroll height, 然后附加?

javascript - 当我单击或选择开始 div 时,如何在 editplus 中突出显示结束 div

php - 如何使用php在数据库中插入动态添加的表单字段