Created
July 16, 2013 17:52
-
-
Save zulfajuniadi/6011006 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
$.fn.serializeObject = function() | |
{ | |
var o = {}; | |
var a = this.serializeArray(); | |
var form = $(this); | |
$.each(a, function() { | |
var input = form.find('[name="'+this.name+'"]'); | |
var multiple = $(input).attr('multiple'); | |
if (multiple) { | |
o[this.name] = o[this.name] || []; | |
o[this.name].push(this.value || ''); | |
} else { | |
o[this.name] = this.value || ''; | |
} | |
}); | |
return o; | |
}; | |
$.fn.populateObject = function(obj, callback) | |
{ | |
var form = $(this); | |
var fields = form.find('select,input,radio,textarea'); | |
$.each(fields, function(){ | |
var t = $(this); | |
switch(t.inputTypeof()) { | |
case 'input' : | |
case 'textarea' : | |
case 'select': | |
if(obj[t.attr('name')] !== undefined) { | |
t.val(obj[t.attr('name')]); | |
} | |
break; | |
case 'radio': | |
case 'checkbox': | |
if(obj[t.attr('name')] !== undefined) { | |
t.prop('checked', true); | |
} | |
break; | |
case 'radio': | |
case 'checkbox': | |
if(obj[t.attr('name')] !== undefined) { | |
t.prop('checked', true); | |
} | |
break; | |
case 'mselect': | |
if(obj[t.attr('name')] !== undefined) { | |
$.each(obj[t.attr('name')], function(key, val){ | |
console.log(val); | |
$('option[value="'+val+'"]', form).attr('selected', 'selected'); | |
}); | |
} | |
break; | |
} | |
}); | |
if($.isFunction(callback)) { | |
callback(obj); | |
} | |
return this; | |
}; | |
$.fn.inputTypeof = function() { | |
if(this.is('select')) { | |
if(this.attr('multiple')) { | |
return 'mselect'; | |
} | |
return 'select'; | |
} else if(this.is('textarea')) { | |
return 'textarea'; | |
} else if(this.is('input[type=radio]')){ | |
return 'radio'; | |
} else if(this.is('input[type=checkbox]')) { | |
return 'checkbox'; | |
} else { | |
return 'input'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment