Reputation: 616
$(document).ready(function(){
var guess;
$('#submit').on("click", function() {
guess = $('#guess-value').val();
$("#value").text(guess);
alert(guess);
});
alert(guess);
});
<div id='game'>
<form id='user-input'>
<input type='text' id='guess-value' placeholder='1-100'></input>
<button id='submit'>Submit</button>
</form>
<h4 id='guess-count'>Attempts left: <span id="attempts">6</span></h4>
</div>
<h4 id='checker'>The value entered is <span id="value">?</span></h4>
I've provided snippets of my HTML and jQuery code above. I am trying to store a number that has been entered into a text field, into a jQuery variable called guess
after pressing a submit button.
The following happens occurs: When I enter a number into the field and press submit, I get an alert showing the value I entered. After closing the event I get another alert that is supposed to show the value of 'guess' and the value is undefined.
This happens even though I declared the variable guess
outside of the click event. Why is this and how do I permanently store the value?
Upvotes: 0
Views: 4806
Reputation: 40038
You are using a <form>
element to ask for user input. The problem with a form, is that when it submits, it wants to navigate away from (or refresh) the page. When the page refreshes, all js is lost.
Simple fix: don't use a form (you can use a DIV instead).
Alternatively, you can tell the form to NOT do its default action of submitting by using event.preventDefault()
:
HTML:
<div id='game'>
<form id='user-input'>
<input type='text' id='guess-value' placeholder='1-100'></input>
<button id='submit'>Submit</button>
</form>
<h4 id='guess-count'>Attempts left: <span id="attempts">6</span></h4>
</div>
<h4 id='checker'>The value entered is <span id="value">?</span></h4>
<input type="button" id="myButt" value="Show Value" />
jQuery:
var guess;
$('#submit').on("click", function (evnt) {
guess = $('#guess-value').val();
$("#value").text(guess);
alert(guess);
evnt.preventDefault();
});
$('#myButt').click(function(){
alert( guess );
});
Further Notes:
Note that the 2nd alert(guess)
in your posted code will occur immediately upon document.ready. I mean, immediately -- as soon as the DOM is ready. Before anything has been put into guess. That is why it returns undefined.
That is probably not what you want. Code example above adds a button to allow you to view that variable's contents when desired.
Upvotes: 4
Reputation: 2316
The function : $("#value").text(guess)
is not corret in this case, replace it with :
$("#value").empty().append(guess);
you should wait to be .ready() in order to submit();
give me feedback please. enjoy :)
Upvotes: 1
Reputation: 32831
The 'guess' variable is out of the click event handler but it's in the ready event handler; So the second alert box will be shown exactly once when the page is loaded. It will then be undefined. The click events will occur later.
Upvotes: 0