Serializing a form without jQuery is not a complex task. All we have to do is to loop through all the elements of a form and select the appropriate ones together with their values. To accomplish this, we'll use the special DOM collection called elements
which comes bound to every form. This collection is a relic of the DOM Level-0 era, but it's really handy. Bear in mind that if you want to use the DOM Level-1 approach, you have to call getElementsByTagName()
for every element type (input
, select
and so on), or, alternatively, use childNodes
. Let's take a look at our code:
function serializeForm(form) { form = document.getElementById(form) || document.forms[0]; var elems = form.elements; var serialized = [], i, len = elems.length, str=''; for(i = 0; i < len; i += 1) { var element = elems[i]; var type = element.type; var name = element.name; var value = element.value; switch(type) { case 'text': case 'radio': case 'checkbox': case 'textarea': case 'select-one': str = name + '=' + value; serialized.push(str); break; default: break; } } return serialized.join('&'); }
We simply fill an array using the name
and value
properties of each form element. Note that we've used a switch
construct on the type
property to select only certain form elements. Finally, we turn our array into a string using an ampersand as a glue token. You can see the demo below.