- <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
- <script type="text/javascript">
- $(function () {
- $("#buttonAdd").bind("click", function () {
- var div = $("<div />");
- div.html(GenerateTextbox(""));
- $("#TextBoxContainer").append(div);
- });
- $("#buttonGet").bind("click", function () {
- var values = "";
- $("input[name=CreateTextbox]").each(function () {
- values += $(this).val() + "\n";
- });
- alert(values);
- });
- $("body").on("click", ".remove", function () {
- $(this).closest("div").remove();
- });
- });
- function GenerateTextbox(value) {
- return '<input name = "CreateTextbox" type="text" value = "' + value + '" /> ' +
- '<input type="button" value="Remove" class="remove" />'
- }
- </script>
- <input id="buttonAdd" type="button" value="Click here to Add Textbox" />
- <div id="TextBoxContainer">
- <!--Textboxes will be added here -->
- </div>
- <input id="buttonGet" type="button" value="Show Values" />
Explanation
In the given example, when we click “buttonAdd” button, it will fire a click event using jQuery. The event will cause it to generate a div and finally will call a function named GenerateTextbox(). The function is going to return textbox and remove button respectively. Whenever you click “buttonAdd”, you will see a textbox and a button nested with a <div> tag.
Finally, this example lets you know how to dynamically create and remove textboxes using jQuery. Subscribe to us to get daily updates.


Kunind OberoiPosted May 20, 2018, 5:47 PM EDT
Is this a joke? haha good one.