Reset hidden fields in HTML form using Javascript

As normal, the clear button is intended for clearing user input, and since hidden inputs are not directly accessible by the user, it doesn’t make sense to allow the user to reset the hidden input’s value. So, the clear form action remains the hidden input values if it varies.

But, in some rare cases, we still need to reset the value of those hidden fields.

Below is several methods I thought of.

1. Cache hidden fields to a safe place

I created a supporter module to support us caching the hidden fields in a form. This requires jQuery to work.

var hiddenResetSupporter = (function() {
    var _form;
    var _initForm = function(formSelector) {
        _form = $(formSelector);
    };
    var _fallbackHiddenFieldsWithTextbox = function() {
        _form.find('input[type=hidden]').each(function() {
            var fallbackTextbox = $('<input>')
                .prop('type', 'hidden')
                .prop('id', 'fallback_textbox_' + $(this).prop('name'))
                .val($(this).val());

            _form.after(fallbackTextbox);
        });
    };

    return {
        setup: function(formSelector) {
            _initForm(formSelector);
            _fallbackHiddenFieldsWithTextbox();
        },
        registerResetEvent: function(callback) {
            var resetPerformElement = _form.find('[type=reset]');
            if (resetPerformElement === undefined) return;

            resetPerformElement.click(function(e) {
                _form.trigger('reset');
                hiddenResetSupporter.resetHiddenFields();
                if (callback) callback();

                e.preventDefault();
            });
        },
        resetHiddenFields: function() {
            _form.find('input[type=hidden]').each(function() {
                $(this).val($('#fallback_textbox_' + $(this).prop('name')).val());
            });
        }
    }
})();

For using example, I created a jsfiddle: https://jsfiddle.net/ducfilan/dbptztsd/

2. Serialize hidden fields to sessionStorage and restore them back in time

Because sessionStorage are widely supported in almost all browsers (for example, even the fastidious bad boy IE supports it in IE versions from 8), you can have a reference here.

So in common situations, you can use sessionStorage as an option here. This is a link to know how it works.

Below is a simple module I created to illustrate how it is done, it still contains several problems of the serialization process.

var hiddenFieldSerializer = (function(){
	var _form;
	var _serializedData;
	var _keyName;

	return {
		setup: function(formSelector, keyName){
			_form = $(formSelector);
			_keyName = keyName;
			_serializedData = [];
		},
		serialize: function(keyName){
			_form.find("input[type='hidden']").each(function() {
				if ($(this).attr('name') ) {
					_serializedData.push($(this).attr('name') + ':' + $(this).val());
				}
			});
			sessionStorage.setItem(_keyName, _serializedData.join());
			return true;
		},
		deserialize: function(){
            if (!sessionStorage.getItem(_keyName)) return;

            var formData = sessionStorage.getItem(_keyName).split(',');

            $.each(formData, function(i, item) {
                var s = item.split(':');
                var elem = _form.find('[name="' + s[0] + '"]');
				elem.val(s[1]);
            });

			return true;
        }
	}
})();

So, you can refer above 2 approaches or what you think of when you need to reset hidden fields in a form.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s