How to create <input type=“text”/> dynamically

后端 未结 12 1053
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 10:47

I want to create an input type text in my web form dynamically. More specifically, I have a textfield where the user enters the number of desired text fields; I want the tex

12条回答
  •  时光取名叫无心
    2020-12-02 11:39

    The core idea of the solution is:

    • create a new input element
    • Add the type text
    • append the element to the DOM

    This can be done via this simple script:

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

    Now the question is, how to render this process dynamic. As stated in the question, there is another input where the user insert the number of input to generate. This can be done as follows:

    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
    Insert number of input to generate: 
    Generated inputs:

    but usually adding just an input is not really usefull, it would be better to add a name to the input, so that it can be easily sent as a form. This snippet add also a name:

    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: 

    Generated inputs:

提交回复
热议问题