jQuery: How to make a clear button?

倖福魔咒の 提交于 2019-12-05 13:18:23
bla

You can modify the code below to suit your needs. It's stolen from this thread anyway.

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>


EDIT (To clear multiple select):

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

    $("#myform #multiple").empty();
});​

jsfiddle v2

If you have a form just add a input with type reset

<input type="reset" value="Clear the Form" />

If you can't use this, then save the default values using .data and retrieve them on you reset the form.

See this example on 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

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

To clear all inputs and remove all options on select elements its more simple, see this example on jsFiddle (same html).

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

    $("#container select").empty();
});

Use Lee Sy En's solution that he found on SO. It's much better and takes care of everything.

$('#myClearButton').click(function() {
  $('#myTextBox').val('');

  $('#myComboBox').val('0'); // set to default value as an example i use 0 
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!