views:

89

answers:

1

I'm trying to add the JavaScript function setTimeout() to my jQuery expression. Without the setTimeout() my function loads a partial view with updated information when I enter text into my textbox. But, it loads the information with every keystroke. My logic is that if I can put in a timer then when the user stops typing, a second later the data is updated.

As you can see I tried to put a setTimeout() in but it doesn't seem to be working.

$(function() {
    $('#DocId').live('keyup', function() {
        setTimeout(var styleValue = $(this).val();
        $('#tableContent').load(
        '/CurReport/TableResults', 
        { style: $(this).val()}), 1000);

    }),
});

Thank you,

Aaron

+4  A: 

You can use .data() and put in a delay timer that resets every keystroke like this:

$('#DocId').live('keyup', function() {
  clearTimeout($.data(this, 'timer'));
  var val = $(this).val();
  var wait = setTimeout(function() {
    $('#tableContent').load('/CurReport/TableResults', { style: val });
  }, 1000);
  $(this).data('timer', wait);
});

This sets a timeout of 1 second every keystroke on the element that it's typed it (can have any number of these going at once). Each keystroke clears the previous timer and sets a new one, so only after 1 complete second of not typing will the function fire.

Note: don't remove the var val = $(this).val(); portion, you need the variable because this is a different context when the function actually executes.

Nick Craver
Thank you for all your help. I've noticed that it has been you that has answered most of my JavaScript questions.
Aaron Salazar