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

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

    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

    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

提交回复
热议问题