1

So referencing this: How to delay the .keyup() handler until the user stops typing?

I came up with the following code. But it does nothing... Any suggestions?

I am trying to get the setTimeout to cancel if the user types something further, so that multiple alerts don't happen, only one when the user finally 'stops' (hopefully).

Thanks!!

var t = 0;  
$('input').keyup(function(){
    clearTimeout(t);
    t = setTimeout(alert($('input').val()),1000);
}
Community
  • 1
  • 1
eatonphil
  • 13,115
  • 27
  • 76
  • 133
  • http://stackoverflow.com/questions/13387958/how-to-stop-ajax-calls-if-theres-an-error-on-a-field-with-a-keyup-trigger/13388050#13388050 – Martin Lyne Nov 23 '12 at 21:46

3 Answers3

2

Replace

t = setTimeout(alert($('input').val()),1000);

with

t = setTimeout(function(){alert($('input').val())},1000);

You were passing the value of the input to setTimeout, while setTimeout needs a function (or a string it can evaluate as code) as first argument.

And replace the last line with }); so that the code compiles.

Demonstration

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
1

You can't get the .val() of a list of elements. $('input') is selecting all inputs on the screen and will only ever give the value of the first one in the list.

This code should work for all inputs, but only run the timeout on the one that fired the event.

var t = 0;  
$('input').keyup(function(){
    var that = this;

    clearTimeout(t);
    t = setTimeout(function() {
        alert($(that).val());
    }, 1000);
}

I hope this helps!

Selosindis
  • 544
  • 5
  • 12
  • Well, jQuery it will get the val of the *first one*, but that's often not what's intended. – JayC Nov 23 '12 at 21:51
0

To prevent confusion on several different inputs, use this reference, keep timeout in data():

var out = $('#out');
$('input').keyup(function() {
    var $this = $(this);
    clearTimeout($this.data('timeout'));
    $this.data('timeout', setTimeout(function() {
        out.append($('<div>').text(($this.attr('id') + ': ' + $this.val())));
    }, 1000));
});​

demo

zb'
  • 8,071
  • 4
  • 41
  • 68