Javascript 动态添加输入元素到表单

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14853779/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 18:09:16  来源:igfitidea点击:

Adding input elements dynamically to form

javascripthtmlforms

提问by xan

I've read many blogs and posts on dynamically adding fieldsets, but they all give a very complicated answer. What I require is not that complicated.

我已经阅读了许多关于动态添加字段集的博客和帖子,但它们都给出了一个非常复杂的答案。我需要的并不复杂。

My HTML Code:

我的 HTML 代码:

<input type="text" name="member" value="">Number of members: (max. 10)<br />
<a href="#" id="filldetails">Fill Details</a>

So, a user will enter an integer value (I'm checking the validation using javascript) in the inputfield. And on clicking the Fill Detailslink, corresponding number of input fields will appear for him to enter. I want to achieve this using javascript.

因此,用户将在input字段中输入一个整数值(我正在使用 javascript 检查验证)。而在点击Fill Details链接时,会出现相应数量的输入字段供他输入。我想使用 javascript 来实现这一点。

I'm not a pro in javascript. I was thinking how can I retrieve the integer filled in by the user in inputfield through the link and displaying corresponding number of input fields.

我不是 javascript 专家。我在想如何input通过链接检索用户在字段中填写的整数并显示相应数量的输入字段。

回答by Xavi López

You could use an onclickevent handler in order to get the input value for the text field. Make sure you give the field an unique idattribute so you can refer to it safely through document.getElementById():

您可以使用onclick事件处理程序来获取文本字段的输入值。确保为该字段提供唯一id属性,以便您可以通过document.getElementById()以下方式安全地引用它:

If you want to dynamically add elements, you should have a container where to place them. For instance, a <div id="container">. Create new elements by means of document.createElement(), and use appendChild()to append each of them to the container. You might be interested in outputting a meaningful nameattribute (e.g. name="member"+ifor each of the dynamically generated <input>s if they are to be submitted in a form.

如果你想动态添加元素,你应该有一个容器来放置它们。例如,一个<div id="container">. 通过创建新元素document.createElement(),并使用appendChild()将每个元素附加到容器中。您可能对输出一个有意义的name属性感兴趣(例如,name="member"+i对于每个动态生成的<input>s,如果它们要在表单中提交。

Notice you could also create <br/>elements with document.createElement('br'). If you want to just output some text, you can use document.createTextNode()instead.

请注意,您还可以<br/>使用document.createElement('br'). 如果你只想输出一些文本,你可以使用document.createTextNode()

Also, if you want to clear the container every time it is about to be populated, you could use hasChildNodes()and removeChild()together.

此外,如果您想在每次即将填充时清除容器,您可以一起使用hasChildNodes()removeChild()

<html>
<head>
    <script type='text/javascript'>
        function addFields(){
            // Number of inputs to create
            var number = document.getElementById("member").value;
            // Container <div> where dynamic content will be placed
            var container = document.getElementById("container");
            // Clear previous contents of the container
            while (container.hasChildNodes()) {
                container.removeChild(container.lastChild);
            }
            for (i=0;i<number;i++){
                // Append a node with a random text
                container.appendChild(document.createTextNode("Member " + (i+1)));
                // Create an <input> element, set its type and name attributes
                var input = document.createElement("input");
                input.type = "text";
                input.name = "member" + i;
                container.appendChild(input);
                // Append a line break 
                container.appendChild(document.createElement("br"));
            }
        }
    </script>
</head>
<body>
    <input type="text" id="member" name="member" value="">Number of members: (max. 10)<br />
    <a href="#" id="filldetails" onclick="addFields()">Fill Details</a>
    <div id="container"/>
</body>
</html>

See a working sample in this JSFiddle.

请参阅此JSFiddle 中的工作示例。

回答by M. Lak

Try this JQuery code to dynamically include form, field, and delete/remove behavior:

试试这个 JQuery 代码来动态包含表单、字段和删除/删除行为:

$(document).ready(function() {
    var max_fields = 10;
    var wrapper = $(".container1");
    var add_button = $(".add_form_field");

    var x = 1;
    $(add_button).click(function(e) {
        e.preventDefault();
        if (x < max_fields) {
            x++;
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box
        } else {
            alert('You Reached the limits')
        }
    });

    $(wrapper).on("click", ".delete", function(e) {
        e.preventDefault();
        $(this).parent('div').remove();
        x--;
    })
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container1">
    <button class="add_form_field">Add New Field &nbsp; 
      <span style="font-size:16px; font-weight:bold;">+ </span>
    </button>
    <div><input type="text" name="mytext[]"></div>
</div>

Refer Demo Here

在这里参考演示