我正在尝试从文本框中获取文本。
我有 2 个不在表单中的输入文本框,我正在尝试检索 value
并将其存储在变量中。
此代码在弹出的警告框中返回undefined
。
<script>
var userPass = document.getElementById('pass');
var userName = document.getElementById('fName');
function submit(){
alert(userPass.value);
}
</script>
当我使用 userName.value
作为警报函数中的参数运行它时,它会工作并显示您在框中键入的内容。
这是 html:
<table id="login">
<tr>
<td><label>User Name</label></td>
</tr>
<tr>
<td colspan="2"><input class="textBox" id="fName" type="text" maxlength="30" required/></td>
</tr>
<tr>
<td id="pass"><label>Password</label></td>
<tr>
<td colspan="2"><input class="textBox" id="pass" type="text" maxlength="30" required/></td>
</tr>
<tr>
<td><input type="button" class="loginButtons" value="Login" onclick="submit();"/>   
<input type="button" class="loginButtons" value="Cancel"/></td>
</table>
最佳答案
你会注意到你在 input
标签中没有值属性。
此外,尽管未显示,但请确保 Javascript 在 html 就位后运行。
关于javascript - 从文本框中获取输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8874960/