A jQuery plugin for displaying Bootstrap form alerts via jQuery events.
Click submit to see an error alert on the example input field.
<form class="form-horizontal" id="example-form"> <div class="form-group"> <label class="control-label" for="inputExample">Example</label> <div class="controls"> <input type="text" id="inputExample" placeholder="Example"> <span data-alertid="example"></span> </div> </div> <div class="form-group"> <div class="controls"> <button type="submit" class="btn btn-primary">Submit</button> </div> </div> </form> <script> $(function(){ $("#example-form").submit(function() { var inputVal = $("#inputExample").val(); $(document).trigger("clear-alert-id.example"); if (inputVal.length < 3) { $(document).trigger("set-alert-id-example", [ { "message": "Please enter at least 3 characters", "priority": "error" }, { "message": "This is an info alert", "priority": "info" } ]); } }); }); </script>
Priority: error/danger, warning, info/notice, success
Enable binding of an element via JavaScript:
$("#example").bsFormAlerts({"id": "example"});
Just add data-alertid="example"
to your element to bind automatically.
<span data-alertid="example"></span>
Name | type | default | description |
---|---|---|---|
id | string | 'bs-form-alert' | the ID of the alert |
outer_query | string | 'div.form-group' | The query used to find the outer div. For Bootstrap 2 set this to 'div.control-group'. |
css_prefix | string | 'has-' | The prefix to use for the alert css classes. For Bootstrap 2 set this to '' (empty string). |
error_css | string | 'danger' | The alert CSS class suffix to use for danger. For Bootstrap 2 set this to 'error'. |
For use with Bootstrap 2, you can override the defaults so you don't have to supply them on the tags.
$.fn.bsFormAlerts.defaults = { alertid: "bs-form-alert", outer_query: "div.control-group", css_prefix: "", error_css: "error" };
Each bound element will listen for a set event that will send the alert data as an object. You can also pass an array of alerts, with any priority, and they will all be displayed in their respective color.
// send an alert to the element with data-alertid='example' $(document).trigger("set-alert-id-example", { "message": "Please enter at least 3 characters", "priority": "error" });
Each bound element will listen for a clear event that will clear the alert and reset the form element.
Note: Notice the dot (.) as separator.
// clear the element with data-alertid='example' $(document).trigger("clear-alert-id.example");
Each bound element will also listen for a clear event that will clear all elements. That's the reason for the dot separator.
// clear all elements $(document).trigger("clear-alert-id");