form2obj()

When dealing with form values over and over, it's often nicer to have them all in a single data structure. When you need to pass a form via XHR, you can use that data structure with something like obj2query() to serialise the form.

It takes just one arguments: either a form node, or the id attribute of a form element and returns a Javascript object.

By combining this code with obj2query, you can optionally submit forms using XHR: <form action="submit.here" method="POST" onsubmit="submit_via_xhr( this.method, this.action, obj2query( form2obj( this ) ), successFunction ); return false">

function form2obj(theForm) {
   var rv = {};

   if (typeof(theForm) == 'string')
      theForm = document.getElementById(theForm);

   if (theForm) {
      for (var i = 0; i < theForm.elements.length; i++) {
         var el = theForm.elements[i];
         if (el.name) {
            var pushValue = undefined;
            if (
               (el.tagName.toUpperCase() == 'INPUT'
                  && el.type.match(/^text|hidden|password$/i))
               || el.tagName.toUpperCase() == 'TEXTAREA'
               || (el.type.match(/^CHECKBOX|RADIO$/i) && el.checked)
            ){
               pushValue = el.value.length > 0 ? el.value : undefined;
            }
            else if (el.tagName.toUpperCase() == 'SELECT') {
               if( el.multiple ) {
                  var pushValue = [];
                  for( var j = 0; j < el.options.length; j++ )
                     if( el.options[j].selected )
                        pushValue.push( el.options[j].value );
                  if( pushValue.length == 0 ) pushValue = undefined;
               } else {
                  pushValue = el.options[el.selectedIndex].value;
               }
            }
            if( pushValue != undefined ){
               if(rv.hasOwnProperty( el.name ))
                  if( rv[el.name] instanceof Array ) {
                     rv[el.name] = rv[el.name].concat( pushValue );
                  }
                  else {
                     rv[el.name] = [].concat( rv[el.name], pushValue );
                  }
               else {
                  rv[el.name] = el.value;
               }
            }
         }
      }
   }
   return rv;
}
Written by Woosta for jif.js