0

I have an input HTML element and want to execute a function when there was an input and if this input didn't changed for 3 seconds.

Code:

$("#search_input").on('input', function() {
  input_value = $("#search_input").val();
  if (input_value != "") {
    setTimeout(function() {
      if (input_value == $("#search_input").val()) {
        alert("still the same :) -> go search");
      }
    }, 3000);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" id="search_input" placeholder="Search...">

The problem is that the handler refresh the input_value so it's always the same. How do you set the input_value as a local variable, so it's not refreshed?

Community
  • 1
  • 1
rwx
  • 696
  • 8
  • 25
  • 2
    Looks like you're just trying to throttle, there are easier ways -> https://jsfiddle.net/adeneo/o11zpub3/ – adeneo Sep 26 '16 at 20:30

3 Answers3

5

You forgot the var declaration:

var input_value = $("#search_input").val();
BrTkCa
  • 4,703
  • 3
  • 24
  • 45
0

while the var thing is true, it's unlikely the issue.

Looks like you want something like the link below, with the key difference being that you are setting a timeout and clearing the timeout as the input changes. By definition, the function above is always firing when input is changing so it's redundant.

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

Community
  • 1
  • 1
Rob Allen
  • 2,871
  • 2
  • 30
  • 48
-4

var var_name = value if it's a normal variable. Like a string or number. Do $var_name = jQuery_object if it's a jQuery object.

HeyBill2
  • 1
  • 2