/
bootstrap.modalform.js
71 lines (58 loc) · 2.21 KB
/
bootstrap.modalform.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
!function ($) {
"use strict"; // jshint ;_;
$( function() {
var modalId = "modal-form-" + parseInt(Math.random() * 1000, 10);
var $cont = $('<div id="'+modalId+'"></div>');
$('body').append( $cont );
$.modalForm = function(options) {
var fields = options.fields || [];
var title = options.title || options.submit;
var submit = options.submit || 'submit';
var $modal, field, type, html = "";
html += "<div class=\"modal hide fade\">";
html += " <form style=\"margin:0\">";
if (title) {
html += " <div class=\"modal-header\">";
html += " <h3>";
html += " "+title;
html += " <button type=\"button\" class=\"close\" data-dismiss=\"modal\" aria-hidden=\"true\">×</button>";
html += " </h3>";
html += " <\/div>";
}
html += " <div class=\"modal-body\">";
while (field = fields.shift()) {
type = /password/.test(field) ? 'password' : 'text';
html += " <input class=\"span3\" type=\""+type+"\" name=\""+field+"\" placeholder=\""+field.replace(/_/g, ' ')+"\"><br \/>";
}
html += " <\/div>";
html += " <div class=\"modal-footer\">";
html += " <button type=\"submit\" class=\"btn btn-primary\">"+submit+"<\/button>";
html += " <\/div>";
html += " <\/form>";
html += "<\/div>";
// make sure that only one modal is visible
$modal = $( html );
$cont.html('').append( $modal );
$modal.modal();
$modal.modal('show');
$modal.on('submit', 'form', function(event){
event.preventDefault();
event.stopPropagation();
var inputs = {};
var $form = $(event.target);
$form.find('[name]').each( function () {
inputs[this.name] = this.value;
});
$modal.trigger('submit', inputs);
});
$modal.on('error', function(event, error) {
$modal.find('.alert').remove();
$modal.find('.modal-body').before('<div class="alert alert-error">'+error.message+'</div>');
});
$modal.on('shown', function() {
$modal.find('input').eq(0).focus()
})
return $modal;
};
})
}( window.jQuery )