Please check: http://jsfiddle.net/ds0jd6gg/
I am trying to implement a "quantity" textbox in a shopping cart, in which when user presses up/down arrows the number is incremented/decremented, and when user presses enter or a quantity box changes i want to implement an ajax request to send the new quantity to backend.
$('.cart-qty').on('keydown', function (e) {
var qty = parseInt($(this).val());
if (e.keyCode == 38) { // up arrow
$(this).val(++qty);
e.preventDefault();
} else if (e.keyCode == 40) { // down arrow
if (qty <= 0) return;
$(this).val(--qty);
e.preventDefault();
} else if (e.keyCode == 13) { // enter key
$(this).blur(); // blur event focuses the pointer out of the textbox
e.preventDefault();
} else if ($.inArray(e.keyCode, [46, 8, 9, 27, 110, 190]) !== -1 ||
(e.keyCode == 65 && e.ctrlKey === true) ||
(e.keyCode >= 35 && e.keyCode <= 40)) { // got this from internet to allow home,bksp etc keys
return;
} else if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { // invalid key pressed in my context
e.preventDefault();
}
}).on('change', function () {
var qty = parseInt($(this).val());
$('.btn-place-order').find('span').html(qty); // just to check in jsfiddle
var item_row = $(this).parents('.cart-row');
item_row.find('.item-qty-count').html(qty); // updates hidden qty fields
$cart.updateQty(item_row.attr('data-item-id'), qty); // implements ajax request
});
When I try this out, the value in quantity box is incremented/decremented correctly, but the "change" event is not fired when I change the qty and press enter/blur from the textbox. Can anybody explain what I'm missing here?
$cartis undefined according to console log.