Elementals.js

Latest Version: 2.0 RC 3 14 March 2017

_.formSerialize Demo

View the Demo live here

elementals.js' _.formSerialize method allows you to serialize the contents of a form so it can be appended safely to a URI or used as data during an AJAX send() command.

The demonstration form is just your typical everyday form. I use the id "demo" on the form element to hook it for trapping onsubmit using _.eventAdd. When the submit fires I serialize the contents of the form and plug them into a DIV#results, cancelling the submit. The code for this isn't exactly rocket science:

var
	results = _d.getElementById('results'),
	form = _d.getElementById('demo');
	
_.eventAdd(form, 'submit', function(e) {
	_.eventPrevent(e);
	_.nodeReplace(results, _.formSerialize(form));
});

I like to store the results of longer operations like Element.getElementById so as not to have to call that slow operation every time I want to manipulate something. Once we have hold of FORM#demo and DIV#results we hook the submit event with _.eventAdd. The handler for that event uses _.eventPrevent so the form does not actually submit, then replaces the current contents of our results box with the serialized version of our form.

Beware that as of the time of this writing, _.formSerialize does NOT support <input type="file">. That operation will likely never be implemented in legacy browsers, but in modern browsers it is possible and may be added to elementals.js at a future date and time.

Side note -- Something to be careful of is that in IE7/earlier if you try to submit with a BUTTON tag that has no type="" normal HTML handling will NOT submit even though type="submit" is supposed to be the default! As such if you care about legacy IE and want to use a BUTTON tag to submit instead of an INPUT, remember to include that attribute!