0

I've been reading other questions and the suggestions I've tried haven't worked for me. I'm trying to have the user enter a number and have it returned in the form of a JS alert (for now). Here is my code:

HTML

<form id="form">
Enter your guess: <input id="guessbox" type="text" name="userguess">
<input id="submitbutton" type="submit" value="Submit">
</form>

JavaScript

var guess = document.getElementById("guessbox").value;
alert(guess);

I keep getting 'null' for the value of my input box and I want the value I enter to be turned into the variable "guess" upon clicking the submit button. I'm sure I'm just missing something basic here.

3
  • 1
    When do you call your js code? Commented May 2, 2014 at 15:57
  • In the example I posted, I guess I don't... however I've tried writing a function with that JS code and I used onClick="thefunction()" on the submit button. I don't really know what to use other than that, which I apparently used incorrectly. Commented May 2, 2014 at 16:01
  • you can use onsubmit=thefunction() Commented May 2, 2014 at 16:03

1 Answer 1

1

You could try:

<form name="form" onSubmit="returnGuess()">
Enter your guess: <input id="guessbox" type="text" name="userguess">
<input id="submitbutton" type="submit" value="Submit">
</form>

Javascript:

function returnGuess(){
    var guess = document.forms["form"]["userguess"].value;
    alert(guess);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Fantastic. That solved it. So the document.forms.value method takes the form name and the input name within the form and returns the value of said input. Out of curiosity, what is the significance of closing the text input tag but not the submit button input tag?
This answer doesn't explain why the original code didn't work. document.getElementById("guessbox") should be equivalent.
I think it was onSubmit in the form that I was really missing. I had tried to use onClick on the submit button without success.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.