Search code examples
javascriptformsjquery-pluginsonkeyup

Submiting form on keyhit. Butut not on every keyhit


i'm currently using this to get the results without enter clicking or Submiting form, just by typing:

<script type="text/javascript">
            $(function() {
                $("#Form_id").bind('keyup',function() {
                    var value = $('#Input_id').val();
                    $.post('process_search.php?term='+value+'&buscar=1',{value:value}, function(data){
                        $("#router").html(data);
                    });
                    return false;
                });
            });
        </script>

Ok, this works great. but has big small little problem: if i type 'hello' sends 4 requests.

In order to solve that, i thought that i could try to detect when a blank space has ben typed and then submit the form. Solution A

Another solution would be to detect when last keyhit was in x miliseconds, solution 2

I like both, but i would apritiate opinions on both, and some help of corse :$

Thanks!


Solution

  • The easiest way would be use setTimeout and clearTimeout so you can delay after x milliseconds have elapsed.

    $(function () {
        var delay;
        $("#Form_id").bind('keyup', function () {
            var value = $('#Input_id').val();
            clearTimeout(delay)
            delay = setTimeout(function () {
                $.post('process_search.php?term=' + value + '&buscar=1', {
                    value: value
                }, function (data) {
                    $("#router").html(data);
                });
            }, 1000);
    
            return false;
        });
    });
    

    Simple example on jsfiddle.