Clear all html controls except some
I have a form consisting of Textbox, Textarea, Password and some kendo dropdowns and dropdowns. I want to clear all controls on a button Clear
except one textbox and one textbox.
I did the following to clear all controls.
$('#btnClear').on('click', function () {
$(this).closest('form').find('input[type=text], textarea, input[type=password]').val('');
});
I don't know how not to clear some of the controls.
source to share
You can achieve functionality in the following way:
Apply some class to the controls you don't want to clean up as shown below:
<div id="parent">
<input type="text" id="textOne" /><br/>
<input type="text" id="textTwo" class="ignoreT" /><br/>
<textarea id="textThree" class="ignoreTA" ></textarea><br/>
<input type="text" id="textFour" class="ignoreT" /><br/>
<button id="clear">Clear</button>
</div>
Now write the following code to clear all controls except ignore class controls:
$('#clear').click(function(){
$(this).closest('form').find('input:not(".ignoreT"), textarea:not("ignoreTA")').val('');
});
or you can apply the same class (suppose ignore) to all controls and write the following code:
$('#clear').click(function(){
$(this).closest('form').find('input, textarea').not('.ignore').val('');
});
See if this works for you or not.
source to share
Use the filtering method .not()
:
Description: Remove items from a set of matched items.
$('#btnClear').on('click', function () {
$(this).closest('form')
.find('input[type=text], textarea, input[type=password]')
.not('foo')
.val('');
});
Where foo
is a selector that refers to exceptions (i.e. controls that you don't want to clean up).
source to share
Try using : not-selector ,
Let someId
is a text field, and otherId
is texxarea, which must not be empty
$('#btnClear').on('click', function () {
$(this).closest('form').find('input:not(#someId),textarea:not(#otherId)').val('');
});
Also you can use generic type class non-empty-elements
with :not
like
$('#btnClear').on('click', function () {
$(this).closest('form')
.find('input[type=text], textarea, input[type=password]')
.not('.non-empty-elements')// filter non-empty-elements
.val('');
});
Please note that you need to add a class non-empty-elements
to those elements that should not be empty
source to share
you can use a selector and define besides one type
$(html).not('span:first').remove();
Ref: 1.jquery remove all elements except the first one,
2 How to remove all <tr> s from a table except the first one using jquery
Css based: - jQuery how to remove or hide all html except selected <div>
source to share