Skip to content

Instantly share code, notes, and snippets.

@phedinkus
Last active December 18, 2015 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phedinkus/5776012 to your computer and use it in GitHub Desktop.
Save phedinkus/5776012 to your computer and use it in GitHub Desktop.
Initialize a bootstrap modal with a form which submits with ajax. This is my first foray using JQuery's widget factory: http://learn.jquery.com/jquery-ui/widget-factory/how-to-use-the-widget-factory/
// Dependent on twitter bootstrap's modal plugin
// Per Bootstrap's api, link to trigger modal should have a data-toggle="modal" attribute
// Modal markup should have one form element
// Initializes with the link or button element which opens the modal
// $("#my-button-element").ajaxModalForm({success: someSuccessFunction, error: someErrorFunction});
$.widget("myNamespace.ajaxModalForm", {
_create: function(){
this.$form = this.element.find("form");
if(this.$form.length !== 1){
console.error("Modal must contain one html form element");
return false;
}
this._initModalHandlers();
},
_initModalHandlers: function () {
var _this = this;
_this._initFormHandlers();
this.element.on("shown", function(event){
$(_this.$form.find("input:visible")[0]).focus();
_this.$form.find("input[type='submit']").button();
}).on("hide", function(){
_this._clearErrorMsgs();
_this.$form[0].reset();
});
},
_initFormHandlers: function () {
var _this = this;
this.$form.on("submit", function(event){
event.preventDefault();
$.ajax({
url: _this.$form.attr('action'),
dataType: 'json',
method: _this.$form.attr("method"),
data: _this.$form.serialize(),
success: function(data){
if (typeof _this.options.success === "function") {
_this.options.success(data);
}
_this.element.modal("hide");
},
error: function(data) {
if (typeof _this.options.error === "function") {
_this.options.error(data);
}
_this._clearErrorMsgs();
_this._addErrorMsgs($.parseJSON(data.responseText));
}
});
});
},
_addErrorMsgs: function (errors) {
for(prop in errors) {
var input = this.$form.find("input[name*='["+prop+"]']");
input.parent().append("<span class='help-inline text-error'>" + errors[prop] + "</span>")
.parent().addClass("error");
}
},
_clearErrorMsgs: function () {
var errorFields = this.$form.find(".error");
$.each(errorFields, function(index, value){
$(value).removeClass('error').find('.help-inline').remove();
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment