Ananth
Ananth

Reputation: 4397

jQuery input event binding

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?

Upvotes: 0

Views: 415

Answers (2)

james emanon
james emanon

Reputation: 11807

I just added this, and it worked: Add a trigger for the "change" event for your capture of the "enter" keyCode, 13.

} else if (e.keyCode == 13) { // enter key
    $(this).blur(); // blur event focuses the pointer out of the textbox
    $(this).trigger('change');
    e.preventDefault();

of course, this is for the "enter" key, you add this trigger whenever you want to call this event.

On why it isn't working for you, could be the preventing of the bubbling with your e.preventDefault's.

Event order of blur and change

Of interest: http://www.nczonline.net/blog/2007/02/06/event-order-of-blur-and-change/

Upvotes: 1

mainstreetmark
mainstreetmark

Reputation: 703

Using val() to set the value of a field does not automatically trigger a change, as a user didn't do the changing. So, add a trigger yourself:

  $(this).val(++qty).trigger('change')

Upvotes: 0

Related Questions