how to add and remove textbox dynamically in javascript?

Today, We want to share with you how to add and remove textbox dynamically in javascript?.In this post we will show you add/remove input fields dynamically with javascript, hear for how to get value from dynamically created textbox in javascript? we will give you demo and example for implement.In this post, we will learn about Dynamically added form field with an example.

Dynamically Adding and Removing Text Boxes using JavaScript

HTML Markup (index.html)

<form id="form1" runat="server">
<input id="btnAdd" type="button" value="add" onclick="AddSuggestionCart()" />
<br />
<br />
<div id="SuggestionCartContainer">
    <!--Textboxes will be added here -->
</div>
<br />
<asp:Button ID="btnPost" runat="server" Text="Post" OnClick="Post" />
</form>

JavaScript Code
client side JavaScript to add and remove the dynamic SuggestionCartes.

<script type="text/javascript">
function GetDynamicSuggestionCart(value){
    return '<input name = "DynamicSuggestionCart" type="text" value = "' + value + '" />' +
            '<input type="button" value="Remove" onclick = "RemoveSuggestionCart(this)" />'
}
function AddSuggestionCart() {
    var div = document.createElement('DIV');
    div.innerHTML = GetDynamicSuggestionCart("");
    document.getElementById("SuggestionCartContainer").appendChild(div);
}
 
function RemoveSuggestionCart(div) {
    document.getElementById("SuggestionCartContainer").removeChild(div.parentNode);
}
 
function RecreateDynamicTextboxes() {
    var comments_data = eval('<%=Values%>');
    if (comments_data != null) {
        var html = "";
        for (var i = 0; i < comments_data.length; i++) {
            html += "<div>" + GetDynamicSuggestionCart(comments_data[i]) + "</div>";
        }
        document.getElementById("SuggestionCartContainer").innerHTML = html;
    }
}
window.onload = RecreateDynamicTextboxes;
</script>

I hope you get an idea about Clear input value on dynamically add/remove inputs.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.