Created
February 26, 2013 14:14
-
-
Save stryju/5038697 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;( function( $, window, document, undefined ){ | |
"use strict"; | |
$.fn.formObject = function( data ){ | |
if ( data ){ | |
this.each( function(){ | |
// we do it only for forms | |
if ( ! /form/i.test( this.tagName )){ | |
return false; | |
} | |
var $form = $( this ); | |
// unserialize | |
$.each( data, function( key, value ){ | |
$form.find( '[name=' + key + ']' ).each( function( index, input ){ | |
var $input = $( input ); | |
switch ( input.type ){ | |
case 'radio': | |
case 'checkbox': | |
// set them only if they have matching value or no value set at all | |
if ( ( $input.prop( 'value' ) && input.value === value ) || ! $input.prop( 'value' )) { | |
$input.prop( 'checked', true ); | |
} | |
break; | |
default: | |
$input.val( value ); | |
} | |
}); | |
}); | |
}); | |
} else { | |
var forms_data = {}; | |
this.each( function(){ | |
var return_obj = {}; | |
// based on http://jsfiddle.net/sxGtM/3/ | |
$.each( $( this ).serializeArray(), function() { | |
if ( return_obj[ this.name ] !== undefined ){ | |
if ( !return_obj[ this.name ].push ){ | |
return_obj[ this.name ] = [ return_obj[ this.name ]]; | |
} | |
return_obj[ this.name ].push( this.value || '' ); | |
} else { | |
return_obj[ this.name ] = this.value || ''; | |
} | |
}); | |
// // we store the values | |
forms_data[ this.id ] = return_obj; | |
return return_obj; | |
}); | |
return forms_data; | |
} | |
}; | |
})( jQuery, window, document ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment