Reputation: 1
I have done a fair bit of searching and keep failing. I'm looking to declare a set of variables that are taken as user input and use these in a number of functions. The only way I have got this to work is to include all the variables in each function, so the script ends up large and repetitive. Can I declare the variables to be used in one place and access them in many functions? Below is a stripped down version with one function in it. Cheers
var df = parseInt(document.getElementById("txt1").value);
var t = parseInt(document.getElementById("txt2").value);
var rh = parseInt(document.getElementById("txt3").value);
var u = parseInt(document.getElementById("txt4").value);
function ffdicalc(df, t, rh, u) {
var ffdi = 2 * Math.exp(-0.45 + 0.987 * Math.log(df) + 0.0338 * t - 0.03458 * rh + 0.0234 * u).toFixed(3);
document.getElementById("result1").innerHTML = ffdi;
}
<!DOCTYPE html>
<html>
<head>
<meta Charset="UTF-8">
<title>FBT</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link
href="https://fonts.googleapis.com/css?family=Catamaran&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
</header>
<main>
<form>
Enter Drought Factor (1 - 10) : <input type="number" id="txt1", min="0" max="10"><br>
Enter Temperature in Degrees Celcius : <input type="number" id="txt2", min="-20" max="60"><br>
Enter Relative Humidity : <input type="number" id="txt3", min="0" max="100"><br>
Enter Wind Speed in Km/s : <input type="number" id="txt4", min="0" max="100"><br>
<button type = "button" onclick="ffdicalc()">Calculate</button>
</form>
<p>
<table class="center">
<tr>
<th><a href="#" title="The FFDI is calculated by...">FFDI</a></th>
</tr>
<tr>
<td id="result1"></td>
</tr>
</table>
</p>
</main>
<div class="wrapper">
<footer>
</footer>
</div>
</body>
</html>
Upvotes: 0
Views: 51
Reputation: 943615
The variables are global. The problem is what you putting in them.
You are copying the values of the inputs to the variables. You are doing this when the script loads, at which time they have only their default values.
You aren't creating a reference to the values of the inputs.
If the user enters a value into any of the inputs then the variables are not updated.
You could store the inputs in the variables (var foo = document.getElementById('foo')
) and then read the current values when you need them (do_something_with(foo.value)
)
Upvotes: 2