rwx rwx - 2 months ago 9
Javascript Question

How to define local variables in a jQuery .on function

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:



HTML



<input type="text" class="form-control" id="search_input" placeholder="Search...">


JS



$("#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);
}
});


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?

Answer

You forgot the var declaration:

var input_value = $("#search_input").val();
Comments