javascript - 提交 HTML 表单时出现“document.getElementById(...) is null”错误
问题描述
我正在尝试提交表单并使用 JavaScript 处理数据,但它不起作用。我在尝试访问表单元素的数据时收到“TypeError: document.getElementById(...) is null”错误。调用了 JavaScript,它只是没有获取表单数据。我也没有在 URL 中看到数据。
我看到一些帖子,人们说源代码应该在代码下面,这不起作用。我尝试将 ID 更改为名称,但没有奏效。我尝试将我的动作更改为不同的东西,但没有奏效。
HTML file:
<!DOCTYPE html>
<html lang="en">
<body>
<script src="/../wsb/src/stockPurchase/stockPurchase.js"></script>
<form autocomplete="off" id="stockPurchaseForm" action="/../wsb/src/stockPurchase/stockPage.html" onsubmit="return purchaseStock()">
<input type="text" id="myStock" placeholder="Stock"><br>
<input type="text" id="amt" placeholder="amt"><br>
<input type="submit" value="Go">
</form>
JavaScript,文件名=stockPurchase.js:
function purchaseStock() {
document.write("purchase stock called"); //checks to see if js is called
stock = document.getElementById("myStock").value;
amt = document.getElementById("amt").value;
document.write("The stock is " + stock + " and the amount is " + amt);
}
function purchaseStock() {
document.write("purchase stock called"); //checks to see if js is called
stock = document.getElementById("myStock").value;
amt = document.getElementById("amt").value;
document.write("The stock is " + stock + " and the amount is " + amt);
}
<form autocomplete="off" id="stockPurchaseForm" action="/../wsb/src/stockPurchase/stockPage.html" onsubmit="return purchaseStock()">
<input type="text" id="myStock" placeholder="Stock"><br>
<input type="text" id="amt" placeholder="amt"><br>
<input type="submit" value="Go">
</form>
预期结果:数据通过表单提交。页面上的 JavaScript 通过使用 document.getElementById(..).value 访问数据,并且我能够打印数据。
实际结果:document.getElementById(..).value 为 null,并且
Form submission canceled because the form is not connected
虽然请注意,调用函数是因为调用了初始 document.write。
解决方案
该document.write()
操作清除 DOM 并调用document.open()
. 如果您尝试编写字符串"The stock is " + stock + " and the amount is " + amt
,则应选择要附加数据的元素并调用.innerText = "The stock is " + stock + " and the amount is " + amt
它。
您可以通过更改document.write()
为console.log()
function purchaseStock() {
console.log("purchase stock called"); //checks to see if js is called
stock = document.getElementById("myStock").value;
amt = document.getElementById("amt").value;
console.log("The stock is " + stock + " and the amount is " + amt);
}
推荐阅读
- qt5 - Qt 中的 VTKWidget 未按预期更新
- c++ - 一次抓住两个单词/短语
- java - 从 Java ResultSet 返回值时出现问题
- javascript - 如何在div内自动向下滚动?
- java - sequencer.startRecording() 没有立即开始?Java MIDI
- error-handling - 处理 GAMS 错误:缺少后缀
- haskell - 不在范围内:类型构造函数或类“-”(以及反转列表时的其他错误)
- asp.net-core - 在 URL 末尾添加斜杠
- java - 如何使用 Java 流打印嵌套列表,其中 Object 包含对其自身的引用列表
- c++ - 用于 ASCII 的环绕式 c++