JSFiddle - React, Tailwind, and code Playground
by abhitalks
HTML
<input id="txt1" type="text" />
<input id="txt2" type="text" />
<br/><br/>
<input type="button" value="1" class="num" />
<input type="button" value="2" class="num" />
<input type="button" value="3" class="num" />
JavaScript
var $txt = null;
$("input[type='text']").on("focus", function(e) {
$txt = $(this);
});
$("body").on("click", function(e) {
if (! $(e.target).is("input")) {
$txt = null;
}
});
$("input.num").on("click", function(e) {
if (! $txt) return false;
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);
// By default assigning the new value will reset selection
// If you want to continue inserting,
// you will have to reselect at the earlier position
// Add 1 to the earlier position bcoz insertion of 1 character...
// will advance your insertion position
$txt[0].setSelectionRange(pos+1, pos+1);
});