我想清除表单中的所有输入和文本区域字段。当使用reset类的输入按钮时,它的工作原理如下:

$(".reset").bind("click", function() {
  $("input[type=text], textarea").val("");
});

这将清除页面上的所有字段,而不仅仅是表单中的字段。我的选择器看起来像什么形式的实际重置按钮生活?


当前回答

$('form').submit(function() {

    var el = $(this);

    $('<button type="reset" style="display:none; "></button>')
        .appendTo(el)
        .click()
        .remove()
    ;

    return false;

});

其他回答

如果你想清空所有的输入框,不管它的类型是什么,那么这是一分钟的步骤

 $('#MyFormId')[0].reset();

有什么理由不应该使用它吗?

$("#form").trigger('reset');

对于jQuery 1.6+:

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .prop('checked', false)
  .prop('selected', false);

对于jQuery < 1.6:

$(':input','#myform')
  .not(':button, :submit, :reset, :hidden')
  .val('')
  .removeAttr('checked')
  .removeAttr('selected');

请看这篇文章: 使用jQuery重置多级表单

Or

$('#myform')[0].reset();

jQuery建议:

要检索和更改DOM属性,例如表单元素的选中、选中或禁用状态,请使用.prop()方法。

我在这里看到的代码和相关的SO问题似乎不完整。

重置表单意味着从HTML中设置原始值,所以我根据上面的代码将其放在一个小项目中:

            $(':input', this)
                .not(':button, :submit, :reset, :hidden')
                .each(function(i,e) {
                    $(e).val($(e).attr('value') || '')
                        .prop('checked',  false)
                        .prop('selected', false)
                })

            $('option[selected]', this).prop('selected', true)
            $('input[checked]',   this).prop('checked',  true)
            $('textarea',         this).each(function(i,e) { $(e).val($(e).html()) })

如果我遗漏了什么或者有什么需要改进的地方,请告诉我。

通过使用JQuery的.trigger()和原生javascript的.reset()的组合,可以将所有表单元素重置为空白状态。

$(".reset").click(function(){
    $("#<form_id>").trigger("reset");
});

将<form_id>替换为form的id来重置。