Run javascript function when user finishes typing instead of on key up?

前端 未结 29 2452
我寻月下人不归
我寻月下人不归 2020-11-22 04:03

I want to trigger an ajax request when the user has finished typing in a text box. I don\'t want it to run the function on every time the user types a letter because that wo

29条回答
  •  余生分开走
    2020-11-22 04:41

    Not sure if my needs are just kind of weird, but I needed something similar to this and this is what I ended up using:

    $('input.update').bind('sync', function() {
        clearTimeout($(this).data('timer'));            
        $.post($(this).attr('data-url'), {value: $(this).val()}, function(x) {
            if(x.success != true) {
                triggerError(x.message);    
            }
        }, 'json');
    }).keyup(function() {
        clearTimeout($(this).data('timer'));
        var val = $.trim($(this).val());
        if(val) {
            var $this = $(this);
            var timer = setTimeout(function() {
                $this.trigger('sync');
            }, 2000);
            $(this).data('timer', timer);
        }
    }).blur(function() {
        clearTimeout($(this).data('timer'));     
        $(this).trigger('sync');
    });
    

    Which allows me to have elements like this in my application:

    
    

    Which get updated when the user is "done typing" (no action for 2 seconds) or goes to another field (blurs out of the element)

提交回复
热议问题