I have a survey in which there are numerous text inputs taking numerical value each of which has a pair of increment/decrement buttons. I have a working function as follows:
HTML:
<div class="text-input-wrapper">
<input type="text" />
<div class="buttons inc-dec">
<button class="increment">Increment</button>
<button class="decrement">Decrement</button>
</div>
</div>
function incDec(btnClass) {
var input = $(this).closest('.text-input-wrapper').find('input');
var inputVal = $(this).closest('.text-input-wrapper').find('input').val();
if ($(this).hasClass('increment')) {
if (inputVal.length == 0) {
($(input).val('1'));
}
else {
inputVal++;
$(input).val(inputVal);
}
} // increment
else if ($(this).hasClass('decrement')) {
if (inputVal.length == 0) {
($(input).val('0'));
}
else {
inputVal--;
$(input).val(inputVal);
}
} // decrement
return false;
} // function incDec
Now I need to enable incrementing and decrementing value using the UP & DOWN keys; I took a stab with the following but with no joy:
$(document).keydown( function(eventObject) {
// UP arrow
if(eventObject.which==38) {
var btnClass = "increment";
} else
// DOWN arrow
if(eventObject.which==40) {
var btnClass = "decrement";
}
incDec(btnClass);
I’d greatly appreciate some clarification as to how to go about firing the increment/decrement using the up/down keys,
Many thanks in advance,
svs
Your problem is that your
incDecfunction is not designed to take the class as an input parameter – it uses the object that calls the event (i.e. the click event on a button).It’s a bit hacky, but how about something like below? You assign the click handler to each button then invoke the relevant button’s click-event.
Here’s a jsfiddle with two such boxes. when you use the up/down arrow keys while inside a text-box it increments/decrements correctly. http://jsfiddle.net/zJBEN/