index.html file
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="1script.js"></script>
<title>Document</title>
</head>
<body>
<form id="form1" name="userInputForm">
<label for="moq">MOQ:</label><br>
<input type="number" id="moq" name="moq" onfocusout=""><br>
<br>
<div id="calculate"><input type="button" name="button" style="width: 8rem; height: 2rem;" value="Calulate" onClick="priceResults()"></div>
</form>
</body>
</html>
scripts.js file
var userInputFormm = document.getElementById("form1");
function priceResults(){
alert(userInputFormm.moq.value);
}
So what I am trying to do is access the form element into a global variable userInputFormm.
but this code gives me an error as shown below when I click Calculate.
when I change it into a local variable to the function priceResults()
, or access it directly using getElementBy in the function, it works perfectly like below.
scripts.js file
Results
I could have gone ahead to create the local variables, but I have a lot of functions to create and I cannot recreate these variables every time, it will make my codes more than I intend them to be.
What am I missing?