Clear all textboxes except few using jQuery
how we can clear all of the text boxes except a few using jQuery.
We have a HTML markup like this:
<div id="parent">
<input type="text" id="one" /><br/>
<input type="text" id="two" /><br/>
<input type="text" id="three" /><br/>
<input type="text" id="four" /><br/>
<button id="clear">Clear</button>
</div>
We have a parent div, which has four input type text elements with specific IDs, one, two, three and four. Now, let’s clear all the textboxes here first.
we can achieve this using jQuery
$('#clear').click(function(){
$('#parent > input:text').val('');
});
Explanation:
1 . Code in the first line
$('#clear').click(function(){
In the above code, we are binding a click event handler to the clear button with id as `clear`.
2 . Code in the second line
$('#parent > input:text').val('');
In the above code, firstly we selecting all the elements of type text inside the parent element using the :text selector.
Then we are setting an empty string as value for all the selected textboxes, in order to clear all the previous values stored, using .val( value ) method.
Now let’s say we have a requirement like, we want to clear all the textboxes except two textboxes with id two and three . In order to achieve this we have to make some modifications in the HTML markup for the textboxes like this:
<div id="parent">
<input type="text" id="one" /><br/>
<input type="text" id="two" class="ignore" /><br/>
<input type="text" id="three" class="ignore" /><br/>
<input type="text" id="four" /><br/>
<button id="clear">Clear</button>
</div>
we have added here a class named “ignore” to both the textboxes which we don’t want to clear. Now, we can achieve our requirement using jQuery like this:
$('#clear').click(function(){
$('#parent > input:text:not(".ignore")').val('');
});
