Skip to content

Instantly share code, notes, and snippets.

@dylants
Last active December 21, 2015 03:38
Show Gist options
  • Save dylants/6243269 to your computer and use it in GitHub Desktop.
Save dylants/6243269 to your computer and use it in GitHub Desktop.
Backbone form submission, serialize the form to set in model (form field names must match model variable names)
/*
* MODEL CODE
*/
formSubmit: function(ev) {
var formValues;
ev.preventDefault();
formValues = this.$("form").serializeObject();
this.model.save(formValues);
}
/*
* SERIALIZE CODE
*/
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
/*
* ADDITIONAL OPTION TO SERIALIZE FORM
*
* This supports "objects" within the form data, through
* the use of brackets to call out object attributes.
* e.g. <input name="myObj[value1]" />
*/
jQuery.fn.serializeJSON = function() {
var json = {};
jQuery.map(jQuery(this).serializeArray(), function(n) {
var _ = n.name.indexOf('[');
if (_ > -1) {
var o = json;
_name = n.name.replace(/\]/gi, '').split('[');
for (var i = 0, len = _name.length; i < len; i++) {
if (i == len - 1) {
if (o[_name[i]]) {
if (typeof o[_name[i]] == 'string') {
o[_name[i]] = [o[_name[i]]];
}
o[_name[i]].push(n.value);
} else o[_name[i]] = n.value || '';
} else o = o[_name[i]] = o[_name[i]] || {};
}
} else {
if (json[n.name] !== undefined) {
if (!json[n.name].push) {
json[n.name] = [json[n.name]];
}
json[n.name].push(n.value || '');
} else json[n.name] = n.value || '';
}
});
return json;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment