Use with the Bootbox.js plugin.
<!-- Include bootbox.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootbox.js/4.2.0/bootbox.min.js"></script>
<button class="btn btn-default" id="loginButton">Login</button>
<!-- The login modal. Don't display it initially -->
<form id="loginForm" method="post" class="form-horizontal" style="display: none;">
<div class="form-group">
<label class="col-md-3 control-label">Username</label>
<div class="col-md-5">
<input type="text" class="form-control" name="username" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Password</label>
<div class="col-md-5">
<input type="password" class="form-control" name="password" />
</div>
</div>
<div class="form-group">
<div class="col-md-5 col-md-offset-3">
<button type="submit" class="btn btn-default">Login</button>
</div>
</div>
</form>
$(document).ready(function() {
$('#loginForm')
.bootstrapValidator({
feedbackIcons: {
valid: 'glyphicon glyphicon-ok',
invalid: 'glyphicon glyphicon-remove',
validating: 'glyphicon glyphicon-refresh'
},
fields: {
username: {
validators: {
notEmpty: {
message: 'The username is required'
}
}
},
password: {
validators: {
notEmpty: {
message: 'The password is required'
}
}
}
}
});
// Login button click handler
$('#loginButton').on('click', function() {
bootbox
.dialog({
title: 'Login',
message: $('#loginForm'),
show: false // We will show it manually later
})
.on('shown.bs.modal', function() {
$('#loginForm')
.show() // Show the login form
.bootstrapValidator('resetForm', true); // Reset form
})
.on('hide.bs.modal', function(e) {
// Bootbox will remove the modal (including the body which contains the login form)
// after hiding the modal
// Therefor, we need to backup the form
$('#loginForm').hide().appendTo('body');
})
.modal('show');
});
});
If you want to use Ajax to submit the form, and then close the modal, we can use the success.form.bv event:
$(document).ready(function() {
$('#loginForm')
.bootstrapValidator({
...
})
.on('success.form.bv', function(e) {
// Prevent form submission
e.preventDefault();
var $form = $(e.target), // The form instance
bv = $form.data('bootstrapValidator'); // BootstrapValidator instance
// Use Ajax to submit form data
$.post($form.attr('action'), $form.serialize(), function(result) {
// ... Process the result ...
// Hide the modal containing the form
$form.parents('.bootbox').modal('hide');
}, 'json');
});
// Login button click handler
$('#loginButton').on('click', function() {
// Same code as above
...
});
});