清除所有html控件,除了一些

时间:2014-08-14 05:08:07

标签: javascript jquery html

我有一个表单,包括Textbox,Textarea,Password和一些kendo下拉列表和组合框。我想清除Clear按钮上的所有控件,除了一个文本框和textarea。

我已完成以下操作以清除所有控件。

$('#btnClear').on('click', function () {
  $(this).closest('form').find('input[type=text], textarea, input[type=password]').val('');
});

我不知道如何不清除某些控件。

5 个答案:

答案 0 :(得分:5)

使用.not()过滤方法:

  

描述:从匹配元素集中删除元素。

$('#btnClear').on('click', function () {
    $(this).closest('form')
           .find('input[type=text], textarea, input[type=password]')
           .not('foo')
           .val('');
});

foo是一个引用异常的选择器(即想要清除的控件)。

答案 1 :(得分:4)

您可以通过以下方法实现该功能:

将一些课程应用于您不想清除的控件,如下所示:

<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>

现在编写以下代码以清除除忽略类控件之外的所有控件:

$('#clear').click(function(){
    $(this).closest('form').find('input:not(".ignoreT"), textarea:not("ignoreTA")').val('');
});

或者您可以将相同的类(假设忽略)应用于所有控件并编写以下代码:

$('#clear').click(function(){
   $(this).closest('form').find('input, textarea').not('.ignore').val('');
});

看看它是否适合你。

答案 2 :(得分:3)

尝试使用 :not-selector

someId是一个文本框,otherId是texxarea,不应为空

$('#btnClear').on('click', function () {
    $(this).closest('form').find('input:not(#someId),textarea:not(#otherId)').val('');
});

此外,您可以使用non-empty-elements和[{1}}之类的公共类,如

:not

请注意,您需要将$('#btnClear').on('click', function () { $(this).closest('form') .find('input[type=text], textarea, input[type=password]') .not('.non-empty-elements')// filter non-empty-elements .val(''); }); 类添加到那些不应该为空的元素

答案 3 :(得分:1)

使用not()

$(this).closest('form').find('input[type=text], textarea, input[type=password]').not('#myControlId1,#myControlId2').val('');

#myControlId1&amp; #myControlId1是您不想清除的控件的ID

答案 4 :(得分:0)

您可以使用selector并定义除

之外的其他内容
$(html).not('span:first').remove();

参考链接: 1. jquery remove all elements except for first one

2 How to remove all the <tr> from a table except the first one using jquery

基于css: - jQuery how to delete or hide all html except selected <div>

相关问题