JSFiddle - React, Tailwind, and code Playground

by oceog

HTML

<input type="text" class="num"/>

JavaScript

//based on script from here: http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea
function setCaretPosition(ctrl, pos) {
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos, pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

function GetCaretPosition(ctrl) {
    var CaretPos = 0; // IE Support
    if (document.selection) {
        ctrl.focus();
        var Sel = document.selection.createRange();
        Sel.moveStart('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0') CaretPos = ctrl.selectionStart;
    return (CaretPos);
}

$(".num").keyup(function(e) {
    var val = this.value;
    if (val.length >= '2') {
        var value = val.substr(0, 2);
        var pos=GetCaretPosition(this);
        $(this).val(value + '/');
        setCaretPosition(this, pos);
        console.log(GetCaretPosition(this));
        if (pos >= 2) {
            setCaretPosition(this, 0);
            return false;
        }
    }
});