I am attempting to port a linear function that I designed in a spreadsheet into HTML and Javascript. It's based on linear least squares where I have to take a Matrix and multiply it by its transformation. At any rate. I am attempting to lay out a basic input system in Javascript/HTML where I can enter in variable data. I have to take in quite a few more inputs, so I am looking for a more maintainable code pattern with less duplication.
In the name of make it work, then make it better. I came up with the following code.
Very new to javascript and the scope is hurting my brain! I am thinking that a dictionary (or similar) where I can pass that to a function then iterate over the values to update my HTML view. But again I am really new to Javascript.
The code also in JS BIN.
window.onload = function() {
var EnameField = document.getElementById('EnameField');
var ENameValue = undefined;
var MnameField = document.getElementById('MnameField');
var MNameValue = undefined;
var CnameField = document.getElementById('CnameField');
var CNameValue = undefined;
var FnameField = document.getElementById('FnameField');
var FNameValue = undefined;
updateNameDisplay();
setInterval(updateNameDisplay, 100);
function updateNameDisplay() {
var thisEValue = EnameField.value || " ";
if (ENameValue != thisEValue) {
document.getElementById('EnameDisplay').innerHTML = ENameValue = thisEValue;
}
var thisMValue = MnameField.value || " ";
if (MNameValue != thisMValue) {
document.getElementById('MnameDisplay').innerHTML = MNameValue = thisMValue;
}
var thisCValue = CnameField.value || " ";
if (CNameValue != thisCValue) {
document.getElementById('CnameDisplay').innerHTML = CNameValue = thisCValue;
}
var thisFValue = FnameField.value || " ";
if (FNameValue != thisFValue) {
document.getElementById('FnameDisplay').innerHTML = FNameValue = thisFValue;
}
}
};
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Test Page</title>
</head>
<body>
<form>
How many E's <input type='text' id='EnameField'><br>
How many M's <input type='text' id='MnameField'><br>
How many C's <input type='text' id='CnameField'><br>
How many F's <input type='text' id='FnameField'><br>
</form>
<hr>
E's: <span id='EnameDisplay'>??</span><br>
M's:<span id='MnameDisplay'>??</span><br>
C's: <span id='CnameDisplay'>??</span><br>
F's: <span id='FnameDisplay'>??</span><br>
</body>