jQuery:如何制作一个清晰的按钮?

我有一个搜索字段,我需要一个清晰的按钮。

我目前有按钮,但我不知道怎么做,

我有6个文本字段,2个combobox和2个多选列表

如何在一个明确的function中清除所有这些? 我知道HTML方式,但我使用Grails并且type =“reset”不起作用。 这就是为什么我想要一个jQuery方法来删除文本框的值,将combobox保留在第一个索引中,并清除多个选择列表中的所有选项。

谢谢你的帮助:D

您可以修改以下代码以满足您的需求。 无论如何它都是从这个线程中偷走的。

的jsfiddle

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

编辑(清除多个选择):

 $('#reset').click(function(){ $(':input','#myform') .not(':button, :submit, :reset, :hidden') .val('') .removeAttr('checked') .removeAttr('selected'); $("#myform #multiple").empty(); });​ 

jsfiddle v2

如果您有表单,只需添加类型为reset的输入

  

如果您不能使用它,则使用.data保存默认值,并在重置表单时检索它们。

在jsFiddle上查看此示例

 $("#container :text").each(function() { var $this = $(this); $this.data("default", $this.val()); }); $("#container select option").each(function() { var $this = $(this); $this.data("default", $this.is(":selected")); }); $("#container :button").click(function() { $("#container :text").each(function() { var $this = $(this); $this.val($this.data("default")); }); $("#container select option").each(function() { var $this = $(this); $this.attr("selected", $this.data("default")); }); }); 

HTML

 

要清除所有输入并删除select元素上的所有选项, 这更简单, 请参阅jsFiddle上的此示例 (相同的html)。

 $("#container :button").click(function() { $("#container :text").val(""); $("#container select").empty(); }); 

使用他在SO上找到的Lee Sy En的解决方案。 它更好,照顾一切。

 $('#myClearButton').click(function() { $('#myTextBox').val(''); $('#myComboBox').val('0'); // set to default value as an example i use 0 });