简体   繁体   中英

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

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.

You could use a JavaScript function to capture the reset button push, save those values as cookies, then return true to complete the reset process. On reload, you can check for those cookies and plug those values back in.

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");

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

});

One simple way to do this is to make reset() temporarily remove the hidden elements from the form while you are resetting

function fixReset() {
    var testForm =  document.getElementById("testForm");
    testForm._nativeReset = testForm.reset;
    testForm.reset = function(){
        var hidden = $('input[type=hidden]',this).detach();
        this._nativeReset();
        $(this).append(hidden);
    }
};
$(document).ready(fixReset);

This way you can still use your native reset buttons if you like. This approach could easily be extended to handle all forms

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM