html:
<div id="search">
<input id="term" type="text" value="enter your search" />
<button id="hit" type="button" name="">Search</button>
</div>
jQuery:
$(document).ready(function() {
var term = $('#term').val();
$('#hit').click(function() {
alert(term);
});
});
The problem is that , no matter what I type in the input field, then hit the button, it always alert the original input value which is “enter your search”.
How can I fix it?
The problem you’re having is that this whole block of code gets executed on the DOM ready event.
var term = $('#term').val();is being evaluated only once and storing ‘enter your search’ in the term variable. This is why no matter what you change the value to, the variable still holds the initial value when the page was rendered.Instead what you should do is something more like the following:
JQuery
In this bit of code, the value of the element with id term is evaluated when the click event listener fires.