Created
December 13, 2013 14:46
-
-
Save beshur/7945344 to your computer and use it in GitHub Desktop.
simple jQuery number input imitator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// simple jQuery input[type='number'] imitator | |
// with callback on number change | |
// | |
// supposed markup: | |
// <div class="elemnt"> | |
// <input type="text" class="target" /> | |
// <span class="arr more"></span> | |
// <span class="arr less"></span> | |
// </div> | |
$.fn.inputNumberize = function(options) { | |
var settings = $.extend({ | |
gt: 0, | |
lt: false, | |
target: "input", | |
callback: function() {} | |
}, options ); | |
this.each(function() { | |
var obj = $(this); | |
var new_count = parseInt(obj.find(settings.target).val()); | |
if (isNaN(new_count)) new_count = settings.gt; | |
if (new_count < settings.gt) new_count = settings.gt; | |
if (settings.lt && new_count > settings.lt) new_count = settings.lt; | |
obj.attr("data-count", new_count); | |
obj.find(settings.target).val(new_count); | |
obj.off("focusout", obj.find(settings.target)) | |
.on("focusout", obj.find(settings.target), function (e) { | |
var new_count = parseInt(obj.find(settings.target).val()); | |
if (isNaN(new_count)) new_count = settings.gt; | |
if (new_count < settings.gt) new_count = settings.gt; | |
if (settings.lt && new_count > settings.lt) new_count = settings.lt; | |
obj.attr("data-count", new_count); | |
obj.find(settings.target).val(new_count); | |
}); | |
obj.off("click", ".arr") | |
.on("click", ".arr", function (e) { | |
e.preventDefault(); | |
var dir = 1; | |
if ($(this).hasClass("less")) dir = -dir; | |
var cur_count = parseInt(obj.find(settings.target).val()); | |
if (!cur_count || isNaN(cur_count)) cur_count = settings.gt; | |
var new_count = cur_count + dir; | |
if (new_count < settings.gt) new_count = settings.gt; | |
if (settings.lt && new_count > settings.lt) new_count = settings.lt; | |
obj.attr("data-count", new_count); | |
obj.find(settings.target).val(new_count); | |
settings.callback.call(obj, [new_count]); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment