Folks, I am newbie to coding, obviously, so having completed few Lynda courses recently on HTML and Javascript, I have hit a wall with my simple HTML page. Basically, what I want is to do a basic calculation with JavaScript to have the user enter the two numbers using HTML form/ input elements and do a basic arithmetic calculation on JS. For some reason the code is not working. Can somebody point me to the right direction as why those input values are not being read by JS? Is getElementById the correct way?
Also, I am using the console.log to dislpay the results as I don't know yet how to have it displayed on the HTML page as a text below the submit button.
The HTML code:
<!DOCTYPE html>
<html>
<head>
<title>Accurate Mass Error Calculator</title>
</head>
<body>
<h1> Accurate Mass Error Calculator </h1>
<p> Please enter the values below for each field:</p>
<form onsubmit="return calculateError()" method="post">
<p> Exact Theoretical Mass: <input id="exactMass" type="number" step="any" name="exactMass"/></p>
<p> Accurate Experimental Mass: <input id="accurateMass" type="number" step="any" name="accurateMass"/></p>
<p> <input id="submitButton" type="submit" name="submit1" value="Calculate" onclick="return calculateError()" /></p>
</form>
<script type="text/javascript" src="ppmError.js"></script>
</body>
</html>
The JS code(ppmError.js):
function calculateError () {
var exactMass=document.getElementById("exactMass");
var accurateMass=document.getElementById("accurateMass");
var ppmError=(accurateMass.value-exactMass.value)/exactMass.value*1000000;
if (isNaN (ppmError) ) {
console.log ("Not a valid Entry! Please try again.")
} else {
console.log(ppmError);
}
}
As Satpal said in the comment you should indeed cast your text to an int with :
For your other question, in your html add an empty paragraph where you want to display your result
<p id="result"></p>
And instead of calling
console.log
you can do :Use solution from singe31, but to prevent reloading of the page after click change type of your button from "submit" to "button" or place "return false;" as the last line of calculateError() function. Otherwise you won't see any change on the page.