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" type="text" />
</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();
//console.log(this);
},
tabFunc: function(e) {
if (e.keyCode === 9) {
var index;
if (e.shiftKey && this === dataSt.inputs[0])
index = dataSt.inputs.length - 1;
else if (!e.shiftKey && this === dataSt.inputs[dataSt.inputs.length - 1])
index = 0;
if (typeof index !== "undefined") {
e.preventDefault();
dataSt.clickFunc.bind(dataSt.inputs[index])();
dataSt.inputs[index].focus();
}
}
},
inputVal: function(id) {
return Number(dataSt.inputs[id].value);
},
updateResult: function() {
dataSt.inputs[dataSt.inputs.length - 1].value = dataSt.inputVal(0) + dataSt.inputVal(1) * dataSt.inputVal(2) + dataSt.inputVal(3);
if (this.value.length >= parseInt(this.getAttribute("maxLength"), 10)) {
var index = parseInt(this.dataset.index, 10) + 1;
//console.log(index);
if (index >= dataSt.inputs.length)
index = 0;
dataSt.clickFunc.bind(dataSt.inputs[index])();
dataSt.inputs[index].focus();
}
},
forEach: function(array, callback, scope) {
for (var i = 0, len = array.length; i < len; i++) {
callback.call(scope, array[i], i, len);
}
},
init: function() {
function addInput(elem, index, max) {
dataSt.inputs.push(elem);
elem.onclick = dataSt.clickFunc;
elem.dataset.index = index;
if (elem.id !== "output") {
elem.oninput = dataSt.updateResult;
elem.value = "0";
elem.setAttribute("maxlength", "2");
/*elem.onkeyup = function(e) {
if (e.keyCode !== 9 && e.keyCode !== 16) {
if (this.value.length >= parseInt(this.getAttribute("maxLength"), 10)) {
var index = parseInt(this.dataset.index, 10) + 1;
//console.log(index);
if (index >= dataSt.inputs.length)
index = 0;
...