Utility class can help you during your development. You can list a functions
that will make your life easier in this class! For example, if you want to check if something is
empty, count the number of characters remaining as the user is typing,
appending a dynamic alert message, and even as simple as resetting
a form fields. The list of your functions may grow overtime
as you need to implement as you go.
Using an Utility class in JavaScript
function CommonUtil() { this.isEmpty = function (str) { return str.length === 0 || str === null || str.trim() === ""; }; this.countCharacters = function (str, elem) { if ($(str).val() == null) $(elem).html($(str).attr("maxlength") - 0); else $(elem).html($(str).attr("maxlength") - $(str).val().length); $(str).keyup(function () { var max = $(str).attr("maxlength"); var currentLen = $(str).val().length; $(elem).html(max - currentLen); if(currentLen == max) { $(elem).parent().html("reached maximum limit").addClass("wobble animated"); } }); }; this.isValueEqual = function (a, b) { return a === b; }; this.removeDisabled = function(elem) { $(elem).click(function() { $(elem).next().removeAttr("disabled"); $(elem).next().removeClass("disabled-style"); }); }; this.alertDiv = function (alertType, alertMessage) { var h = ""; h += '<div class="alert alert-'+alertType+' alert-dismissible" role="alert">'; h += '<button type="button" class="close" data-dismiss="alert" aria-label="Close">'; h += '<span aria-hidden="true">Ă—</span>'; h += '</button>'; h += '<strong>'+alertMessage+'</strong>'; h += '</div>'; return h; }; this.resetFormFields = function(formId) { $(formId).trigger("reset"); }; }