首页 > 解决方案 > 提交 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。

标签: javascripthtml

解决方案


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

推荐阅读