【问题标题】:How to create <input type=“text”/> dynamically如何动态创建 <input type="text"/>
【发布时间】:2011-08-05 02:40:07
【问题描述】:

我想在我的网络表单中动态创建输入类型文本。更具体地说,我有一个文本字段,用户可以在其中输入所需文本字段的数量;我希望以相同的形式动态生成文本字段。

我该怎么做?

【问题讨论】:

    标签: javascript html forms webforms


    【解决方案1】:

    使用 JavaScript:

    var input = document.createElement("input");
    input.type = "text";
    input.className = "css-class-name"; // set the CSS class
    container.appendChild(input); // put it into the DOM
    

    【讨论】:

    • 对不起,我无法在我的表单上显示它?我制作了一个函数,当单击添加按钮时会触发该函数。但我无法弄清楚如何从用户类型的文本字段中获取 vlaue 来创建要创建的文本字段的数量。 . ?如果我还想为这些动态创建的文本字段分配一个 css 类怎么办。 . ?
    • 我在示例中添加了一些代码以显示将其附加到 DOM 并将 CSS 类添加到动态创建的元素。
    • 这不会创建&lt;input ....&gt; 它会创建&lt;input ...&gt;&lt;/input&gt;
    【解决方案2】:

    使用 Javascript,您只需要document.createElementsetAttribute

    var input = document.createElement("input");
    input.setAttribute('type', 'text');
    

    然后您可以使用appendChild 将创建的元素附加到所需的父元素。

    var parent = document.getElementById("parentDiv");
    parent.appendChild(input);
    

    【讨论】:

      【解决方案3】:

      创建用户给定的输入字段数


      1. 从用户那里获取文本字段的数量并将其分配给一个变量。

        var no = document.getElementById("idname").value


      1. 要创建输入字段,请使用createElement 方法并指定元素名称,即“输入”作为参数,如下所示并将其分配给变量。

        var textfield = document.createElement("input");


      1. 然后为变量分配必要的属性。

        textfield.type = "text";

        textfield.value = "";


      1. 最后使用appendChild 方法将变量附加到表单元素。这样输入元素将在表单元素本身中创建。

        document.getElementById('form').appendChild(textfield);


      1. 循环 2,3 和 4 步骤以创建用户在表单元素中指定的所需数量的输入元素。

        for(var i=0;i<no;i++) {           
            var textfield = document.createElement("input");
            textfield.type = "text"; textfield.value = "";
            document.getElementById('form').appendChild(textfield);
        }
        

      这是完整的代码

      function fun() {
          /*Getting the number of text fields*/
          var no = document.getElementById("idname").value;
          /*Generating text fields dynamically in the same form itself*/
          for(var i=0;i<no;i++) {
              var textfield = document.createElement("input");
              textfield.type = "text";
              textfield.value = "";
              document.getElementById('form').appendChild(textfield);
          }
      }
      <form id="form">
          <input type="type" id="idname" oninput="fun()" value="">
      </form>

      【讨论】:

        【解决方案4】:

        也许document.createElement(); 方法就是你要找的。​​p>

        【讨论】:

          【解决方案5】:

          请参阅此答案以获取非 JQuery 解决方案。刚刚帮了我!

          Adding input elements dynamically to form

          【讨论】:

          • 非常好。我不明白为什么人们一直在用 jquery 举例。谢谢。
          【解决方案6】:

          解决方案的核心思想是:

          • 创建一个新的input 元素
          • 添加类型text
          • 将元素附加到 DOM

          这可以通过这个简单的脚本来完成:

          var input = document.createElement('input');
          input.setAttribute('type', 'text');
          document.getElementById('parent').appendChild(input);
          

          现在的问题是,如何使这个过程动态化。如问题中所述,还有另一个输入,用户在其中插入要生成的输入数量。这可以按如下方式完成:

          function renderInputs(el){
            var n = el.value && parseInt(el.value, 10);
            if(isNaN(n)){
              return;
            }
            
            var input;
            var parent = document.getElementById("parent");
            
            cleanDiv(parent);
            for(var i=0; i<n; i++){
              input = document.createElement('input');
              input.setAttribute('type', 'text');
              parent.appendChild(input);
            }
          }
          
          function cleanDiv(div){
            div.innerHTML = '';
          }
          Insert number of input to generate: </br>
          <input type="text" onchange="renderInputs(this)"/>
          
          <div id="parent">
          Generated inputs:
          </div>

          但是通常只添加一个输入并没有什么用处,最好在输入中添加一个名称,以便可以轻松地作为表单发送。 这个sn -p还要加个名字:

          function renderInputs(el){
            var n = el.value;
            var input, label;
            var parent = document.getElementById("parent");
            cleanDiv(parent);
            
            el.value.split(',').forEach(function(name){
              input = document.createElement('input');
              input.setAttribute('type', 'text');
              input.setAttribute('name', name);
              label = document.createElement('label');
              label.setAttribute('for', name);
              label.innerText = name;
              parent.appendChild(label);
              parent.appendChild(input);
              parent.appendChild(document.createElement('br'));
            });
          }
          
          function cleanDiv(div){
            div.innerHTML = '';
          }
          Insert the names, separated by comma, of the inputs to generate: </br>
          <input type="text" onchange="renderInputs(this)"/>
          <br>
          Generated inputs: </br>
          <div id="parent">
          
          </div>

          【讨论】:

            【解决方案7】:

            您可以根据他们输入的文本字段的数量循环执行类似的操作。

            $('<input/>').attr({type:'text',name:'text'+i}).appendTo('#myform');
            

            但为了获得更好的性能,我会先创建所有 html,然后只将其注入 DOM 一次。

            var count = 20;
            var html = [];
            while(count--) {
              html.push("<input type='text' name='name", count, "'>");
            }
            $('#myform').append(html.join(''));
            

            编辑此示例使用 jQuery 附加 html,但您也可以轻松修改它以使用 innerHTML。

            【讨论】:

            • 可能会提到这取决于 jQuery,因为问题没有指定 jQuery。
            【解决方案8】:

            您可以使用createElement() 方法来创建该文本框

            【讨论】:

              【解决方案9】:

              我认为以下链接会对您有所帮助。如果您想动态生成字段并同时删除它们,您可以从这里获得帮助。我有同样的问题,所以我得到了答案

              $(function() {
                      var scntDiv = $('#p_scents');
                      var i = $('#p_scents p').size() + 1;
              
                      $('#addScnt').live('click', function() {
                              $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
                              i++;
                              return false;
                      });
              
                      $('#remScnt').live('click', function() { 
                              if( i > 2  ) {
                                      $(this).parents('p').remove();
                                      i--;
                              }
                              return false;
                      });
              });
              

              http://jsfiddle.net/jaredwilli/tZPg4/4/

              【讨论】:

              • 这段代码的删除部分相当不完善。如果您添加 2 个输入并删除中间一个,您最终会得到 2 个具有相同 ID 的输入。最好删除带有i--; 的行此外,如果您将其放入由 PHP 处理的表单中,您将不得不分别处理原始和附加输入字段。
              【解决方案10】:

              你可以使用 ES6 退出

                var inputs = [
                      `<input type='checkbox' id='chbox0' onclick='checkboxChecked(this);'> <input  type='text' class='noteinputs0'id='note` + 0 + `' placeholder='task0'><button  id='notebtn0'                     >creat</button>`, `<input type='text' class='noteinputs' id='note` + 1 + `' placeholder='task1'><button  class='notebuttons' id='notebtn1' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 2 + `' placeholder='task2'><button  class='notebuttons' id='notebtn2' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 3 + `' placeholder='task3'><button  class='notebuttons' id='notebtn3' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 4 + `' placeholder='task4'><button  class='notebuttons' id='notebtn4' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 5 + `' placeholder='task5'><button  class='notebuttons' id='notebtn5' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 6 + `' placeholder='task6'><button  class='notebuttons' id='notebtn6' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 7 + `' placeholder='task7'><button  class='notebuttons' id='notebtn7' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 8 + `' placeholder='task8'><button  class='notebuttons' id='notebtn8' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 9 + `' placeholder='task9'><button  class='notebuttons' id='notebtn9' >creat</button>`
                  ].sort().join(" ");
                 document.querySelector('#hi').innerHTML += `<br>` +inputs;
              &lt;div id="hi"&gt;&lt;/div&gt;

              【讨论】:

                【解决方案11】:
                • 查询并获取容器 DOM 元素

                • 创建新元素

                • 将新元素放入文档树

                //Query some Dib region you Created
                let container=document.querySelector("#CalculationInfo .row .t-Form-itemWrapper");
                let input = document.createElement("input");
                
                //create new Element  for apex
                input.setAttribute("type","text");
                input.setAttribute("size","30");
                containter.appendChild(input); // put it into the DOM
                

                【讨论】:

                • @murb 你也可以贡献
                【解决方案12】:
                <button id="add" onclick="add()">Add Element</button>
                
                <div id="hostI"></div>
                
                <template id="templateInput">
                    <input type="text">
                </template>
                
                <script>
                    function add() {
                
                        // Using Template, element is created
                        var templateInput = document.querySelector('#templateInput');
                        var clone = document.importNode(templateInput.content, true);
                
                        // The Element is added to document
                        var hostI = document.querySelector('#hostI');
                        hostI.appendChild(clone);
                    }
                
                </script>
                

                HTML 模板现在是生成动态内容的推荐标准。

                【讨论】:

                • 值得注意的是,IE 不支持此功能。 MDN docs
                【解决方案13】:

                试试这个:

                function generateInputs(form, input) {
                  x = input.value;
                  for (y = 0; x > y; y++) {
                    var element = document.createElement('input');
                    element.type = "text";
                    element.placeholder = "New Input";
                    form.appendChild(element);
                  }
                }
                input {
                  padding: 10px;
                  margin: 10px;
                }
                <div id="input-form">
                  <input type="number" placeholder="Desired number of inputs..." onchange="generateInputs(document.getElementById('input-form'), this)" required><br>
                </div>

                上面的代码有一个表单,其中有一个接受数字的输入:

                <form id="input-form">
                  <input type="number" placeholder="Desired number of inputs..." onchange="generateInputs(document.getElementById('input-form'), this)"><br>
                </form>
                

                输入运行一个函数onchange,这意味着当用户输入一个数字并点击提交时,它运行一个函数。 要求用户在提交之前用值填写输入。该值必须是数字。提交后,父表单和输入将传递给函数:

                ...
                generateInputs(document.getElementById('input-form'), this)
                ...
                

                generate then 根据输入中的给定值循环:

                ...
                x = input.value;
                for (y=0; x>y; y++) {
                ...
                

                然后它在每个循环中在表单内生成一个输入:

                ...
                var element = document.createElement('input');
                element.type = "text";
                element.placeholder = "New Input";
                form.appendChild(element);
                ...
                

                我还添加了一些 CSS 样式以使 inputs 看起来不错,还添加了一些 placeholders。 阅读更多关于创建元素createElement()

                https://www.w3schools.com/jsref/met_document_createelement.asp

                阅读更多关于 for 循环的信息:

                https://www.w3schools.com/js/js_loop_for.asp

                【讨论】:

                  猜你喜欢
                  • 1970-01-01
                  • 2011-12-28
                  • 2013-06-28
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2018-07-15
                  • 1970-01-01
                  • 2013-06-13
                  相关资源
                  最近更新 更多