May 4, 2012

Simplest way to prevent form reset method from clearing hidden inputs in IE8

Question by mikez302

The Javascript reset method for forms is not supposed to affect hidden inputs, but in IE8 and IE7 it does anyway. Does anyone know a way to make it behave properly?

I know I can do it by looping through individual inputs or by remembering the values before resetting the form and then restoring them but I am wondering if anyone can come up with a simpler way. Feel free to use jQuery if it will make your solution simpler. You can see an example at http://jsfiddle.net/Ddtz4/.

According to the author of the plugin, this is supposedly not an IE bug and the effect of the reset method on elements without initial values is undefined.

Answer by mikez302

I am thinking of something like this, using jQuery:

$(document).delegate("form", "resetForm", function() {
    $(this).find("input[type=hidden]").each(function() {
        $(this).prop("defaultValue", $(this).val());
    });
    this.reset();
});

Whenever I want to reset a form, I can do this:

$("#whateverForm").trigger("resetForm");

Answer by Starx

The following snippet seem to be working for IE8 too

$("#testInput").val('foo');
$("#testForm")[0].reset();
$("#result").html($("#testInput").val());

Update:

Why dont you create a custom reset function() instead:

$("#resetbutton").on("click", function() {
    var form = $(this).closest('form');
    form.find("input:not(:hidden)").val('');
    form.find("select").prop('selected', false);
    // so on

});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!