2

I use this simple Jquery code to get element from a div and then to change it thanks to a php script :

$(document).ready(function(){
    $("#description").keyup(function(){
    var recherche = $(this).val();

    $.ajax({
        type : "GET",
        url : "result.php",
        data : {motclef: recherche},
        success: function(server_response){
        $("#resultat").html(server_response).show();
        }
    });
});

});

Problem is some changes can happend without pressing any key (copy/past ...). I have tried with .change() but it is triggered only when the focus of the element is lost.

user1836529
  • 209
  • 1
  • 2
  • 9
  • You keep track of values an compare them – kidwon Nov 30 '12 at 14:57
  • 1
    The `input` event is what you want. – pimvdb Nov 30 '12 at 14:57
  • 1
    You might want to look at delaying the AJAX call so there has to be a delay of a certain amount of time between key presses before it sends the request; sending one request per `keyup` event is potentially going to result in a lot of requests being sent. – Anthony Grist Nov 30 '12 at 15:04

1 Answers1

1

You can tell jQuery to bind to multiple events in one call like this. Once you are inside the method you can filter behavior based on the event type. When handling paste it's usually a good idea to delay the function call slightly to allow the browser to do everything it needs to first.

Edit

I've updated the answer based on this stackoverflow answer in order to handle autocomplete.

$("#description").on("keyup paste cut focus change blur",function (event) {

    var $this = $(this),
        delay = 0

    // Add delay for cut/paste
    if (event.type === "paste" || event.type === "cut") {
        delay = 5;
    }

    // Record the current value of the text box.
    if (event.type === "focus" || event.type === "change") {
        this.previousvalue = this.value;
    }

    // Trigger the change event if the value is now different.
    if (event.type === "blur") {
        if (this.previousvalue !== this.value){
            $this.change();
            return false;
        }
    }

    window.setTimeout(function () {

        var recherche = $this.val();

        $.ajax({
            type : "GET",
            url : "result.php",
            data : {motclef: recherche},
            success: function(server_response){
                $("#resultat").html(server_response).show();
            }
        });                  

    }, delay);
});
Community
  • 1
  • 1
James South
  • 10,147
  • 4
  • 59
  • 115