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

后端 未结 12 1008
伪装坚强ぢ
伪装坚强ぢ 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:38

    I think the following link will help you. If you want to generate fields dynamically and also want to remove them on the same time you can get the help from here. I had the same question, So i got the answer

    $(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/

    0 讨论(0)
  • 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<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>

    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: </br>
    <input type="text" onchange="renderInputs(this)"/>
    <br>
    Generated inputs: </br>
    <div id="parent">
    
    </div>

    0 讨论(0)
  • 2020-12-02 11:41

    To create number of input fields given by the user


    1. Get the number of text fields from the user and assign it to a variable.

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


    1. To create input fields, use createElement method and specify element name i.e. "input" as parameter like below and assign it to a variable.

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


    1. Then assign necessary attributes to the variable.

      textfield.type = "text";

      textfield.value = "";


    1. At last append variable to the form element using appendChild method. so that the input element will be created in the form element itself.

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


    1. Loop the 2,3 and 4 step to create desired number of input elements given by the user inside the form element.

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

    Here's the complete code

    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>

    0 讨论(0)
  • 2020-12-02 11:41

    You could do something like this in a loop based on the number of text fields they enter.

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

    But for better performance I'd create all the html first and inject it into the DOM only once.

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

    Edit this example uses jQuery to append the html, but you could easily modify it to use innerHTML as well.

    0 讨论(0)
  • 2020-12-02 11:43

    With 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
    
    0 讨论(0)
  • See this answer for a non JQuery solution. Just helped me out!

    Adding input elements dynamically to form

    0 讨论(0)
提交回复
热议问题