MLH Quick Calculate
by MegaScience
HTML
<div class="container">
<div class="inputs">
<input id="first" type="text" /> +
<input id="second" type="text" /> *
<input id="third" type="text" /> +
<input id="forth" type="text" />
</div>
<div>
<input id="output" />
</div>
</div>
CSS
input {
width: 25px;
border: 1px solid black;
}
/* http://stackoverflow.com/a/631114/5857393 */
input#output {
display: block;
box-sizing: border-box;
width: 100%;
}
.container {
float: right;
margin-top: 50px;
margin-right: 20px;
}
JavaScript
var dataSt = {
inputs: {},
clickFunc: function() {
this.select();
},
getInpVal: function (id) {
return Number(dataSt.inputs[id].value);
},
updateResult: function() {
dataSt.inputs.output.value = dataSt.getInpVal("first") + dataSt.getInpVal("second") * dataSt.getInpVal("third") + dataSt.getInpVal("forth");
},
init: function() {
function addInput(id, index, arr) {
var curr = dataSt.inputs[id] = document.getElementById(id);
curr.onclick = dataSt.clickFunc;
if (id !== "output") {
curr.oninput = dataSt.updateResult;
curr.value = "0";
curr.setAttribute("maxlength", "2");
}
// http://stackoverflow.com/a/21811463/5857393
if(index === 0) {
curr.focus();
dataSt.firstInp = curr;
curr.onkeydown = function (e) {
if (e.keyCode === 9 && e.shiftKey) {
e.preventDefault();
dataSt.lastInp.focus();
}
}
}
else if(index === (arr.length - 1)) {
// http://stackoverflow.com/a/29738635/5857393
dataSt.lastInp = curr;
curr.onkeydown = function (e) {
if (e.keyCode === 9 && !e.shiftKey) {
e.preventDefault();
dataSt.firstInp.focus();
}
}
}
}
["first", "second", "third", "forth", "output"].forEach(addInput);
}
};
dataSt.init();
//alert(JSON.stringify(dataStore.inputs));