jQuery is a JavaScript library, which helps us in making our Webpages more interactive. If you are completely new to jQuery, I will recommend you to first go through the following blogs to get an overview of jQuery.
- jQuery Library
- jQuery Syntax
- jQuery Events
Adding UI elements dynamically is very easy with jQuery. We have jQuery append() method, which allows us to append the content at the end of the specified element and the remove() method, which helps us in removing the content from the specified element.
Let us understand append() and remove() better with the help of a simple example.
- <html>
-
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
- </head>
-
- <body> <button id="Add">Click to add textbox</button> <button id="Remove">Click to remove textbox</button>
- <div id="textboxDiv"></div>
- <script>
- $(document).ready(function() {
- $("#Add").on("click", function() {
- $("#textboxDiv").append("<div><br><input type='text'/><br></div>");
- });
- $("#Remove").on("click", function() {
- $("#textboxDiv").children().last().remove();
- });
- });
- </script>
- </body>
-
- </html>
Output
Now, when you click on the "Click to add textbox", a textbox gets appended and when you "Click to remove textbox", the last added textbox is removed.
As you can see in the screenshot above, the highlighted area is our division with Id "textboxDiv". Initially, the div does not contain any element or textbox.
When the add button is clicked, we capture it with the help of Id selector and we have bound on click function. The function appends <div><br><input type='text'/><br></div> to the textboxDiv division with the help of append() method of jQuery. Similarly, we are using the remove method to remove the textbox.
Please refer to the image, given below for the explanation of remove() method, used in the example, shown above.
In this way, the elements can be easily added and removed in jQuery just on a button click or some other events too. The more you play with jQuery code, the more you learn. I hope this blog helped you.
You might also like.
Stay tuned. Keep learning.