I have a C#.NET MVC3 web app and I have some common jQuery functionality across my pages and want to modularize it. I don't know how to do this. Below is an example of the code I'm using. You will notice several controls have functions assigned to events. Each View I have will do this, BUT the controls (and number of controls) will be different. There may be 1 control that needs the event added to or there may be 10.
$(document).ready(function () {
$("#Description").keyup(function () {
disableEnableSave();
});
$("#DueDate").change(function () {
disableEnableSave();
});
$("#EndDate").keyup(function () {
disableEnableSave();
});
});
Below is the disableEnableSave() code. Similar issue, inside that code, there may 1 control to work against or 10.
function disableEnableSave() {
var text = $("#Description").val();
var text1 = $("#DueDate").val();
var text2 = $("#EndDate").val();
var textlength = text.length;
var textlength1 = text1.length;
var textlength2 = text2.length;
if (textlength > 0 && textlength1 > 0 && textlength2 > 0) {
$("#thePageSubmit").removeAttr("disabled");
}
else {
$("#thePageSubmit").attr("disabled", "disabled");
}
document.title = document.title.replace("*", "");
document.title = document.title + "*";
return true;
}
I am not a jQuery or JavaScript expert but I gotta think there's a way to encapsulate this in a .js file and pass in some parameters. Any Ideas?
Live demo: http://jsfiddle.net/g3azJ/3/
$.fn.disableFalseInput = function(list) {
var _this = $(this),
required = $(list);
required .bind("keyup change", function() {
var available = true;
$.each(required , function(k, v) {
if (v.value.length == 0) {
available = false;
return false;
}
});
if (available) {
_this.removeAttr("disabled")
} else {
_this.attr("disabled", "disabled");
}
}).first().trigger("keyup");
}
Define the button that needs some inputs as required:
$("#thePageSubmit").disableFalseInput("#Description, #DueDate, #text2");
#thePageSubmit
is the submit button that will be disabled, and the parameter are the fields required. This can be used on each button, or whatever you got.