JSFiddle - React, Tailwind, and code Playground

HTML

<input type="button" value="Test Button"><br /><br />
<input name="txt1" id="txt1"> Input 1 <br />
    <input name="txt2" id="txt2"> Input 2 <br />
        <input name="txt3" id="txt3"> Input 3 <br />
            <input name="txt4" id="txt4"> Input 4 <br />
                <input name="txt5" id="txt5"> Input 5 <br />

JavaScript

// any time a textarea gets focus, set the ID
$('input').focus(function(){
   focusID = $(this).attr('id');
});

// when the button is clicked
$('input[type="button"]').click(function(){    
    // insert the value into the input
    insertAtCaret(focusID,$(this).val())
});

function insertAtCaret(areaId,text) {
    var txtarea = document.getElementById(areaId);
    var scrollPos = txtarea.scrollTop;
    var strPos = 0;
    var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ? 
        "ff" : (document.selection ? "ie" : false ) );
    if (br == "ie") { 
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        strPos = range.text.length;
    }
    else if (br == "ff") strPos = txtarea.selectionStart;
    
    var front = (txtarea.value).substring(0,strPos);  
    var back = (txtarea.value).substring(strPos,txtarea.value.length); 
    txtarea.value=front+text+back;
    strPos = strPos + text.length;
    if (br == "ie") { 
        txtarea.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -txtarea.value.length);
        range.moveStart ('character', strPos);
        range.moveEnd ('character', 0);
        range.select();
    }
    else if (br == "ff") {
        txtarea.selectionStart = strPos;
        txtarea.selectionEnd = strPos;
        txtarea.focus();
    }
    txtarea.scrollTop = scrollPos;
}