I have a search field, and I need a clear button.
I currently have the button, but I don't know how to do it,
I have 6 textfields, 2 comboboxes, and 2 multiple select lists
How do I clear all of them in one clear function?? I know the HTML way, but I am using Grails and the type="reset" does not work. That's why I want a jQuery way of deleting textboxes' values, leaving the combobox in the first index, and clear all options from the multiple select list.
Thanks for the help :D
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();
});
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With