I have a form with a standard reset button coded thusly:
Trouble i
basically none of the provided solutions makes me happy. as pointed out by a few people they empty the form instead of resetting it.
however, there are a few javascript properties that help out:
these store the value that a field had when the page was loaded.
writing a jQuery plugin is now trivial: (for the impatient... here's a demo http://jsfiddle.net/kritzikratzi/N8fEF/1/)
(function( $ ){
$.fn.resetValue = function() {
return this.each(function() {
var $this = $(this);
var node = this.nodeName.toLowerCase();
var type = $this.attr( "type" );
if( node == "input" && ( type == "text" || type == "password" ) ){
this.value = this.defaultValue;
}
else if( node == "input" && ( type == "radio" || type == "checkbox" ) ){
this.checked = this.defaultChecked;
}
else if( node == "input" && ( type == "button" || type == "submit" || type="reset" ) ){
// we really don't care
}
else if( node == "select" ){
this.selectedIndex = $this.find( "option" ).filter( function(){
return this.defaultSelected == true;
} ).index();
}
else if( node == "textarea" ){
this.value = this.defaultValue;
}
// not good... unknown element, guess around
else if( this.hasOwnProperty( "defaultValue" ) ){
this.value = this.defaultValue;
}
else{
// panic! must be some html5 crazyness
}
});
}
} )(jQuery);
// reset a bunch of fields
$( "#input1, #input2, #select1" ).resetValue();
// reset a group of radio buttons
$( "input[name=myRadioGroup]" ).resetValue();
// reset all fields in a certain container
$( "#someContainer :input" ).resetValue();
// reset all fields
$( ":input" ).resetValue();
// note that resetting all fields is better with the javascript-builtin command:
$( "#myForm" ).get(0).reset();
$( "#container" ).resetValue()
won't work. always use $( "#container :input" )
instead.