I am trying to submit a form and handle the data with JavaScript, but it is not working. I am getting a 'TypeError: document.getElementById(...) is null' error when trying to access the data of the form element. The JavaScript IS called, it is just not getting the form data. I am not seeing the data in the URL either.
I saw a few posts where people said that the source code should be below the code, and that did not work. I tried changing the IDs to names, and that did not work. I tried changing my action to different things and that did not work.
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, filename=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>
Expected results: Data is submitted through form. JavaScript on page accesses the data by using document.getElementById(..).value, and I am able to print the data.
Actual results: document.getElementById(..).value is null, and
Form submission canceled because the form is not connected
Though note, the function IS called, since the initial document.write is called.