In this article I will explain how to dynamically add and remove TextBoxes dynamically and how to get value of dynamically created TextBoxes using jQuery.
HTML Markup
The HTML Markup consists of an HTML Button to add dynamic TextBoxes using jQuery, an HTML DIV for holding the dynamic TextBoxes and an HTML Button for fetching and displaying the values of dynamic TextBoxes using JavaScript.
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
Client Side Scripting
Below is the client side jQuery script to add and remove the dynamic TextBoxes using jQuery.
Adding a dynamic TextBox
When the Add Button is clicked, it creates a dynamic HTML DIV and then gets the HTML string consisting of a dynamic TextBox and a Button by making a call to the GetDynamicTextBox function.
The HTML string is assigned to the DIV and then the DIV is appended as child element to the container DIV.
Note: While creating the dynamic TextBoxes I am assigning a constant name attribute DynamicTextBox to all TextBoxes. The values of the dynamic TextBoxes will be fetched using its name attribute.
Removing a dynamic TextBox
The Remove Button is assigned a class attribute. Using the class attribute value as jQuery Selector, a click event handler is assigned to the Remove Button.
When the Remove Button is clicked, first its parent HTML DIV is determined and then the HTML DIV is removed from the container DIV.
Fetching values of dynamic TextBoxes
When the Get Button is clicked, a jQuery loop is executed over all TextBoxes with the name DynamicTextBox and their values are displayed using JavaScript Alert message box.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
</script>
Screenshots
Demo
Downloads