在JavaScript中存储和返回HTML表单中的输入变量

时间:2022-11-16 07:26:33

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:

我一直在阅读其他问题,我尝试过的建议对我没用。我正在尝试让用户输入一个数字并以JS警报的形式返回(暂时)。这是我的代码:

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.

我继续为输入框的值获取'null',并且我想在输入的值变为“猜测”时单击提交按钮。我确定我只是遗漏了一些基本的东西。

1 个解决方案

#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);
}

#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);
}