Created
September 20, 2010 01:28
-
-
Save dwarfmondo/587306 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Requires the following attributes be set: step, min, and max on the input | |
input_number: function() { | |
if (!$('input[type=number]').length) { | |
return; | |
} | |
function getStep(el) { | |
return parseInt($(el).attr('step')) || 1; | |
} | |
function stepUp(el) { | |
var step = getStep(el); | |
var max = parseInt($(el).attr('max')); | |
var val = parseInt($(el).val()); | |
val = val + step; | |
if (val <= max) { | |
if (el.stepUp) { | |
el.stepUp(step); | |
} | |
else { | |
// there is a max value set | |
if (val != max) { | |
val = val + step; | |
if (val > max) { | |
val = max; // if the increase is greater than max, then set to max so that we don't go over | |
} | |
} | |
$(el).val(val); | |
} | |
} | |
} | |
function stepDown(el) { | |
var step = getStep(el); | |
var min = parseInt($(el).attr('min')); | |
var val = parseInt($(el).val()); | |
val = val - step; | |
if (val >= min) { | |
if (el.stepDown) { | |
el.stepDown(step); | |
} | |
else { | |
// there is a max value set | |
if (val != min) { | |
val = val - step; | |
if (val < min) { | |
val = min; // if the decrease is less than min, then set to min so that we don't go under | |
} | |
} | |
$(el).val(val); | |
} | |
} | |
} | |
function isNumber(obj) { | |
return (obj === +obj) || (obj.toString() === '[object Number]'); | |
} | |
$('input[type=number]').keydown(function(ev){ | |
if (isNumber(parseInt(this.value))) { | |
var keyCode = ev.keyCode; | |
if (keyCode == '38') { | |
// up arrow | |
stepUp(this); | |
} | |
else if (keyCode == '40') { | |
// down arrow | |
stepDown(this); | |
} | |
} | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment