Reputation: 476
Here is the code that I am having problems with. Below it I'll add an explanation:
$(function() {
var $input = $("#input");
var input = $input.val();
var $go = $("#go");
$go.click(function() {
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
The code above is a dummie example to represent my actual question, no more background is needed.
So I have one input type="number" id="input"
in which you input a number, and a button type="button" id="go"
.
In my jQuery, I first declare $input
which holds the element #input
, then input
which holds the value of the element #input
, and finally $go
which holds the element #go
.
Below that I have a function, that says that when I click on #go
, I should be able to alert(input)
.
Now, this code does not do that. In my head this makes perfect sense, but apparently it doesn't work.
Upvotes: 2
Views: 1488
Reputation: 66103
That is because you are declaring input
outside the click function, which means the value (simply an empty string) is set at runtime and will not be updated. You should define input
within your click event handler:
$(function() {
var $input = $("#input");
var $go = $("#go");
$go.click(function() {
var input = $input.val();
alert(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
Upvotes: 3
Reputation: 20905
First of all, StackOverflow seems to block alerts origination from the code snippet, it will be much easier to output them to the console instead so you can keep track of things.
Your code can be simplified way down without the need for many variables.
But your main problem was the fact that the input value was not getting reset when the click event happened but was getting picked up on page load, meaning it would be stuck at ''
.
$(function() {
$("#go").click(function() {
var input = $("#input").val();
console.log(input);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<main>
<input type="number" id="input">
<button type="button" id="go">GO!</button>
</main>
Upvotes: 1