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.

Absolute position table with padding

Today, I have a task of widening the tables to match 100% browser width to view more contents while keeping other elements stay the as they were.

pjimage

The problem is, I have so many tables to do (about 20 pages including that kind of table). I am too lazy to edit all of those pages. It really takes time and potential to introduce bugs.

So, I choose javascript and CSS to help me out.

Firstly, those tables have the class named “table_wide”.

We will use the CSS absolute position’s power of ignorance. We can make the table to be absolute with 100% percent width. But the problem is, it also ignores padding or margin. So our table will be stuck to the left and right edges.

Well, challenge accepted.

Absolute position ignores everything but it has top, right, bottom and left instead. However, top, right, bottom and left are not adapted to its width. So we cannot use padding properly.

We will use what we have to acquire what we want.


$(".table_wide").each(function(){
var paddingInPx = 10;
var windowWidthInPx = $(window).width();

// Calculate the width of table.
var thisWidthInPercent = 100 - (100/windowWidthInPx*2*paddingInPx);

// Create an empty div to fill up the space the absolute table occupied in the past.
$(this).after('<div style="height: ' + this.offsetHeight + 'px;"></div>');
$(this).wrap('<div style="position: absolute; width: ' + thisWidthInPercent + '%; left: ' + paddingInPx + 'px"></div>');
});

.table_wide {
    display: block;
    overflow: auto;
}

Well done! Challenge accomplished.

Jsfiddle: https://jsfiddle.net/ducfilan/p961moLd/

How to debug/inspect your mobile web page on a real mobile device (with or without real device)

When developing web apps for with mobile support, we usually use Device toolbar (Ctrl + Shift + M) on Google Chrome Developer Tools. But, the problem is that sometimes our layout or javascript code work on Device toolbar but not a real device and there is no dev tool on mobile browsers.

Luckily, Chrome Developer Tools provides us a really useful tool to debug our web page on a real android device on our desktop totally like what we do on desktop web pages.

Installation and interacting with Remote debugging are described here.

In case you don’t have an Android device in hand. You could use an Emulator. It works perfectly with me.

I use Genymotion, it’s really fast and stable.

You can use any mobile browser and be able to debug your web pages on that browser.

You can install browsers to the Genymotion Emulator by drag and drop your .apk file to the emulator screen.

Or you can install Google Play Store and get them downloaded just like a normal device.

The processes are described here.

Goodluck!

Data structures in javascript – part 1: Stack and queue

maxresdefault

StackQueue có lẽ là 2 trong những dạng cấu trúc dữ liệu phổ biến nhất được sử dụng hàng ngày. Chúng ta nghĩ đến stack ở việc Back trong trình duyệt, khi Undo trong trình soạn thảo văn bản; nghĩ đến Queue trong trình tự thực hiện của việc đăng kí nhiều event cho 1 element.