How do I add textboxes dynamically in Javascript?

后端 未结 8 883
感情败类
感情败类 2020-12-15 20:43

By default I have 5 textboxes. When a user clicks on a button, one textbox should be added.

How could I do this?

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-15 21:25

    Javascript Function

    function add() {
    
    //Create an input type dynamically.
    var element = document.createElement("input");
    
    //Create Labels
    var label = document.createElement("Label");
    label.innerHTML = "New Label";     
    
    //Assign different attributes to the element.
    element.setAttribute("type", "text");
    element.setAttribute("value", "");
    element.setAttribute("name", "Test Name");
    element.setAttribute("style", "width:200px");
    
    label.setAttribute("style", "font-weight:normal");
    
    // 'foobar' is the div id, where new fields are to be added
    var foo = document.getElementById("fooBar");
    
    //Append the element in page (in span).
    foo.appendChild(label);
    foo.appendChild(element);
    }
    

    Html part,

    And, Its done!

提交回复
热议问题