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

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

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

    $('').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("");
    }
    $('#myform').append(html.join(''));
    

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

提交回复
热议问题