Skip to content

Instantly share code, notes, and snippets.

@kanduvisla
Created March 28, 2012 10:30
Show Gist options
  • Save kanduvisla/2225277 to your computer and use it in GitHub Desktop.
Save kanduvisla/2225277 to your computer and use it in GitHub Desktop.
jQuery Input Field Incrementer
(function (jQuery) {
jQuery.fn.extend({
incrementButtons:function (options) {
var defaults = {
minVal:null,
maxVal:null,
incClass:'inc',
decClass:'dec',
callback: function(value){}
}
var getNumVal = function (element) {//get numeric value of an object
var value = Number(element.val());
return isNaN(value) ? 0 : value;
}
var correctValue = function (min, max, value) {
var checkMin = min != null && !isNaN(0 + min);
var checkMax = max != null && !isNaN(0 + max);
if (value > max && checkMax) {
return max;
}
if (value < min && checkMin) {
return min;
}
return value;
}
var options = jQuery.extend(defaults, options);
return this.each(function () {
var obj = jQuery(this);
// Wrap obj:
obj.wrap('<div class="increment"></div>');
// Create buttons:
var decButton = obj.after('<a href="#" class="' + options.decClass + '">-</a>').next();
var incButton = obj.after('<a href="#" class="' + options.incClass + '">+</a>').next();
// Focus value:
var focusValue;
incButton.click(function (e) {
e.preventDefault();
obj.val(correctValue(options.minVal, options.maxVal, (getNumVal(obj) + 1)));
options.callback(getNumVal(obj));
});
decButton.click(function (e) {
e.preventDefault();
obj.val(correctValue(options.minVal, options.maxVal, (getNumVal(obj) - 1)));
options.callback(getNumVal(obj));
});
obj.focus(function () {
focusValue = obj.val();
});
obj.blur(function () {
obj.val(correctValue(options.minVal, options.maxVal, getNumVal(obj)));
if(obj.val() != focusValue)
{
options.callback(getNumVal(obj));
}
});
});
}
});
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment