Search code examples
jquerykeypressfocusout

Jquery ajax request on focusout and enter


I want to request a ajax query when focus on input field is lost or when the user hits enter in the input field.

I have following code for doing so

function editVK() {
    var input = $('.check_vk');
    input.keydown(function () {
        // DO some markup
    }).focusout(function () {
        // execute ajax in function
        calculateVolleKist($(this));
        return false;
    }).on('keypress', function (e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
           // execute ajax in function   
           calculateVolleKist($(this));
           return false;
        }
    });
}

function calculateVolleKist(elem) {
    var regel = elem.closest("tr");
    var article_id = regel.attr('data-article_id');
    var basket_id = regel.attr('data-basket_id');
    var vk = parseFloat(formatToDecimal(elem.val()));

    $.ajax({
        url: 'beltramibasket.php?action=wijzig_volle_kist&basket_id='+basket_id+'&article_id='+article_id+'&vk='+vk,
        type: 'GET',
        dataType: "html",
        async: true,
        success: function(data) {
            $('.basket_body').html("");
            $('.basket_body').html(data);
            editVK();
        }
    });
}

When using this code, my first change in the input fires 1 request. My second change fires 2 request, my 3 request fires 4 request and so on unit my browser chrashes.

EDIT Included 2nd function. My response is HTML , I clear the body and put html back into the body. After that I execute the function editVK again. Because I want to trigger other request when editing the input box.


Solution

  • Try to insert this before your jQuery code:

    input.unbind('keydown');
    input.unbind('focusout');
    input.unbind('keypress');
    

    not 100% sure if this is the source of your problem but it's possible that your are registering the events every time new.