JSFiddle - React, Tailwind, and code Playground
by Nibin George
HTML
<div class="wrapper">
<input type="button" class="tab" value="Tab"/>
<input type="text" class="ans1" style="border-color:black">
<div class="def1"><i>Hundreds</i></div>
<input type="text" class="ans2" style="border-color:black">
<div class="def2"><i>Tens</i></div>
<input type="text" class="ans3" style="border-color:#000;">
<div class="def3"><i>Ones </i><b style="margin-left:30px;"></b> </div>
<input type="text" class="ans4" style="border-color:#000;">
<input type="button" class="num" id="one" value="1" />
<input type="button" class="num" id="two" value="2" />
<input type="button" class="num" id="three" value="3" />
<input type="button" class="num" id="four" value="4" />
<input type="button" class="num" id="five" value="5" />
<input type="button" class="num" id="six" value="6" />
<input type="button" class="num" id="seven" value="7" />
<input type="button" class="num" id="eight" value="8" />
<input type="button" class="num" id="nine" value="9" />
<input type="button" class="num" id="zero" value="0" />
<input type="button" class="clear" value="Clear"/>
<input type="button" class="delete" value="Back"/>
<input type="button" class="tab" value="Tab"/>
</div>
CSS
input, select, textarea {
border: 1px solid #b8b8b8;
}
input:focus, select:focus, textarea:focus {
border: 1px solid #323232;
}
a {
color: #cc0000;
text-decoration: none;
}
a:focus {
text-decoration: underline;
}
JavaScript
var focusAbles = $('.wrapper').find('input[type=text]');
$('.tab').on('mousedown', function (e) {
e.preventDefault();
var inFocus = $(':focus');
if (inFocus.length) {
var focusIndex = focusAbles.index(inFocus);
if (focusIndex + 1 < focusAbles.length) {
focusAbles.eq(focusIndex + 1).focus();
} else {
focusAbles.eq(0).focus();
};
} else {
focusAbles.eq(0).focus();
};
});
var $txt = null; // Keep track of currently active input
$("input[type='text']").on("focus", function(e) {
$txt = $(this); // Click any input, the tracker will point to it
});
$("body").on("click", function(e) {
// Click anywhere else apart from the inputs, clear the tracker
if (! $(e.target).is("input")) {
$txt = null;
}
});
$(".num").on("click", function(e) {
if (! $txt) return false; // If tracker is cleared, just return
var prev = $txt.val();
var num = this.value;
var pos = $txt[0].selectionStart;
var newValue = prev.substring(0, pos) + num + prev.substring(pos);
$txt.val(newValue);
$txt[0].focus();
$txt[0].setSelectionRange(2, 2);
console.log(pos);
});
$('.delete').on('click',function() {
var $myInput = $txt;
$myInput.val($myInput.val().slice(0, -1));
});
$('.clear').on('click',function() {
$txt.val('');
});