JQuery: How to make a clear button?

I have a search box and I need a clear button.

I currently have a button, but I don’t know how to do it,

I have 6 text fields, 2 combo boxes and 2 lists with several lists

How to clear all of them in one clear function? I know the HTML way, but I use Grails, and type = "reset" does not work. So I want jQuery to delete the values ​​of the text fields, leaving the combo box in the first index and removing all options from the multiple choice list.

Thanks for the help: D

+4
source share
3 answers

You can change the code below to suit your needs. He stole that 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 selections):

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

jsfiddle v2

+7
source

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

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

If you cannot use this, save the defaults with .data and extract them to you reset in the form.

See this example in 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 parameters on select elements, it is simpler, see this example in jsFiddle (same html).

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

Use the Lee Sy En solution that he found on SO. It is 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 }); 
+1
source

All Articles