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?

1
  • 2
    Looks like you're just trying to throttle, there are easier ways -> jsfiddle.net/adeneo/o11zpub3 Commented Sep 26, 2016 at 20:30

3 Answers 3

5

You forgot the var declaration:

var input_value = $("#search_input").val();
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

-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.

4 Comments

That's just a naming convention... it's not required by the language and can't be the issue here.
@JasonP Ik but like you said, its convention
This doesn't answer the question, at best it belongs in the comment section.
Yes, and your "answer" does not answer the question or solve the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.