For the example here, I am using a DIV and a Table as containers and each of these controls have 2 HTML Input boxes each.
Note: If you are using Asp.Net textbox controls in your project, the methods will have similar effect.
Now, let's see our example.
First, add the jQuery library (Google CDN) file inside the <script> tag in the <head> section of the Web page.
<head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> </head>
<!DOCTYPE html> <html> <head> <title>Clear All Textbox Values using jQuery</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <%--STYLE INPUT BOXES--%> <style> body { font:13px Verdana; font-weight:normal; } body input { padding:3px; width:100px; border:solid 1px #CCC; border-radius:2px; -moz-border-radius:2px; -webkit-border-radius:2px; } </style> </head> <body> <p>Textboxes inside a <strong>DIV</strong> element</p> <div id="divContainer"> <%-- YOU CAN ADD ASP.NET TEXTBOX CONTROLS. --%> <%-- HOWEVER, MAKE SURE ITS AN ASP.NET PROJECT --%> <asp:TextBox id="tb1" runat="server"></asp:TextBox> <%--HTML INPUT BOX.--%> <input type="text" id="tb2" /> </div> <p>Textboxes inside a <strong>TABLE</strong> element</p> <table id="tblContainer" cellpadding="0" cellspacing="0"> <tr> <td style="padding:0 5px 0 0"><input type="text" id="tb3" /></td> <%-- HERE'S AN ASP.NET TEXTBOX CONTROLS INSIDE A TABLE ELEMENT. --%> <td><asp:TextBox ID="tb4" runat="server"></asp:TextBox></td> </tr> </table> <p><input type="button" id="btClearAll" value="Clear All" /></p> </body>
// SCRIPT TO FIND TEXTBOXES AND CLEAR THE VALUES IN IT. <script> $('#btClearAll').click(function() { // SEARCH TEXTBOX CONTROLS INSIDE A DIV AND CLEAR THE VALUES. $('#divContainer').find('input:text').each(function() { $('input:text[id=' + $(this).attr('id') + ']').val(''); } ); // SEARCH TEXTBOX CONTROLS INSIDE THE TABLE AND CLEAR THE VALUES. $('#tblContainer').find('input:text').each(function() { $(this).val(''); } ); }); </script> </html>
Try it yourself
The below Textboxes are inside a DIV element
Textboxes inside a TABLE element
Some Value | Name of the Book |
---|---|
jQuery | |
AngularJS |
In the above script, I am using three jQuery methods to accomplish the task, that is clearing all the values inside textboxes. The method .find() will search input boxes inside the containers. That is why I have attached the method with the container’s id.
$('#divContainer').find('input:text')
The second method is jQuery .each(). The method loops through each textbox inside a container.
The jQuery .val() method assign some text or values to each textbox control. This method takes a value as parameter, and in this context the value is nothing (.val('')). Therefore, I am assigning no value to the textboxes inside the containers. And all this is done with the click of a single button.