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

ran*_*ech 4 jquery button clear

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

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

我有6个文本字段,2个组合框和2个多选列表

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

谢谢你的帮助:D

Bru*_*oLM 8

如果你有一个表单只需添加一个类型的输入 reset

<input type="reset" value="Clear the Form" />
Run Code Online (Sandbox Code Playgroud)

如果您不能使用它,则使用.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"));
  });
});
Run Code Online (Sandbox Code Playgroud)

HTML

<div id="container">
    <input type="text" value="default" />
    <select>
        <option>Op1</option>
        <option selected="true">Op2</option>
    </select>
    <select multiple="true" size="5">
        <option>Op1</option>
        <option selected="true">Op2</option>
    </select>

    <input type="button" value="reset" />
</div>
Run Code Online (Sandbox Code Playgroud)

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

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

    $("#container select").empty();
});
Run Code Online (Sandbox Code Playgroud)


bla*_*bla 7

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

的jsfiddle

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

<form id='myform'>
    <input type='text' value='test' />
    <select id='single'>
        <option>One</option>
        <option selected="true">Two</option>
    </select>
    <select multiple="true" size="5" id='multiple'>
        <option>One</option>
        <option selected="true">Two</option>
    </select>
    <input type='button' id='reset' value='reset' />
</form>
Run Code Online (Sandbox Code Playgroud)


编辑(清除多个选择):

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

    $("#myform #multiple").empty();
});?
Run Code Online (Sandbox Code Playgroud)

jsfiddle v2