jQuery清除Div中的值

3
我有一个DIV,其中包含许多输入文本。
我需要一种在jQuery 1.3.2中清除所有输入值的方法onclick。
因此,当我单击特定链接时,该DIV内所有输入的值都将被清除。
我没有任何示例代码,我只需要知道是否有一种方法可以清除特定DIV内输入的所有值(不是在FORM中,而是在DIV中)。
6个回答

7

是的,有这样的

像这样的HTML

<div id="div_id">
    <input type="text" value="foo" />
    <input type="text" value="foo" />
    <input type="text" value="foo" />
    <input type="text" value="foo" />
</div>

然后是jQuery。
$('#div_id input[type="text"]').val('');

working demo


1
这里唯一的问题是它无法清除密码、复选框和单选按钮字段。 - Jeremy B.
@Jeremy B 的观点很好。在这种情况下,原帖的作者需要循环并创建一个 switch case 来处理不同类型的情况。 - mcgrailm
在这种情况下,$('#div_id input[type="text"']).trigger('reset'); 就可以解决问题了。 - Tharaka Nuwan

3
这些输入是什么?文本框?也许是这个。
$("#DivID input:text").val("");

Demo


1

要清除 div 内的表单元素值,请使用以下方法

 function clear_form_elements(id_name) {
  jQuery("#"+id_name).find(':input').each(function() {
    switch(this.type) {
        case 'password':
        case 'text':
        case 'textarea':
        case 'file':
        case 'select-one':       
            jQuery(this).val('');
            break;
        case 'checkbox':
        case 'radio':
            this.checked = false;
    }
  });
}

0

尝试使用输入文本元素的val属性将其设为空白。

类似这样:

$("input[type='text']", "#<YOUR_DIV_ID>").val("");

e.g:

<div id="textDiv">
    <input type="text" Value="1"/> <br/>
    <input type="text" Value="2"/> <br/>
    <input type="text" Value="3"/> <br/>
    <input type="text" Value="4"/> <br/>
    <input type="text" Value="5"/> <br/>
    <input type="text" Value="6"/> <br/>
    <a name="clickMe" href="javascript:void(0)">Empty Boxes</a>
</div>

<script type="text/javascript">
    $(function(){
     $("a[name='clickMe']").click(function(){
        $("input[type='text']", "#textDiv").val("");
     });
    });
</script>

查看实时示例 @: http://jsfiddle.net/DKwy8/


0
$('linkselector').onClick(function() {
    $('#DivId input').val('');
});

只会获取值,而不会设置它。 - mcgrailm
谢谢,我忘记加引号了,可恶,试图快速得到答案。 - Jeremy B.

0

尝试

HTML

<div id="myDiv">
    <input type="text" value="One">
    <input type="text" value="Two">
    <input type="text" value="Three">
</div>
<a href="#" name="ClearDiv" id="clearDiv">Clear</a>

jQuery

$('a#clearDiv').bind('click', function() {        
    var $div = $('div#myDiv');
    $('input[type="text"]', $div).each(function() {     
      $(this).val('');
    });

});

工作演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接