Skip to content

Instantly share code, notes, and snippets.

@iddar
Last active December 31, 2015 04:49
Show Gist options
  • Select an option

  • Save iddar/7936418 to your computer and use it in GitHub Desktop.

Select an option

Save iddar/7936418 to your computer and use it in GitHub Desktop.
formToJSON es una funcion para que retorna los datos de un form para debolver un objeto JSON. La funcion regresa un objeto. Esta funcion toma se basa en la version de: http://onwebdev.blogspot.com/2011/05/serializing-form-without-jquery.htm a la cual le agrege los nuevos typos de html5
// formToJSON: Encapsula el formulario en un objeto JSOM
// params: un objeto DOM o vacio para el primer formulario del documento
// return: un objeto JSON con el contenido del formulario
function formToJSON( form ) {
form = document.querySelector( form ) || document.forms[0];
var elems = form.elements;
var i, len = elems.length;
var jsonForm = {};
for( i = 0 ; i < len ; i++ ) {
var element = elems[i];
var type = element.type;
var name = element.name;
var value = element.value;
switch(type) {
case 'color':
case 'date':
case 'datetime':
case 'datetime-local':
case 'email':
case 'month':
case 'number':
case 'range':
case 'search':
case 'tel':
case 'time':
case 'url':
case 'week':
case 'text':
case 'radio':
case 'tel':
case 'textarea':
case 'select-one':
jsonForm[ name ] = value;
break;
case 'checkbox':
if ( element.checked )
jsonForm[ name ] = value;
break;
default: break;
}
}
return jsonForm;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment