Reputation: 1902
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?
Upvotes: 9
Views: 90255
Reputation:
I know this is a pretty old thread but still I thought I'll post an answer,
Change your jQuery from this:
$(document).ready(function() {
var term = $('#term').val();
$('#hit').click(function() {
alert(term);
});
});
To this:
$(document).ready(function() {
$('#hit').click(function() {
var term = $('#term').val();
alert(term);
});
});
<div id="search">
<input id="term" type="text" value="enter your search" />
<button id="hit" type="button" name="">Search</button>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Just declare the variable term onclick not before it is clicked. Becoz otherwise it takes the value of the input before the button was clicked.
Upvotes: 1
Reputation: 3123
This worked for me after trouble For int
function getValue(){
$("qty").value = parseInt($("qty").value);
}
For string
function getValue(){
$("qty").value = $("qty").value;
}
Upvotes: 0
Reputation: 14029
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
$(document).ready(function() {
$('#hit').click(function() {
alert($('#term').val());
});
});
In this bit of code, the value of the element with id term is evaluated when the click event listener fires.
Upvotes: 23
Reputation: 3745
Because you created the variable just when the document is ready.. try to create the variable "term" inside the click function...
$(document).ready(function() {
$('#hit').click(function(event) {
var term = $('#term').val();
alert(term);
});
});
Upvotes: 7
Reputation: 16961
You need to get the value on click
, rather than document ready
$(document).ready(function() {
$('#hit').click(function() {
var term = $('#term').val();
alert(term);
});
});
Upvotes: 4