JSFiddle - React, Tailwind, and code Playground

by john_s

HTML

<input type="text" />

JavaScript

// Try pasting in the following (with the surrounding white space
// and then press the tab key:
// 		 $10,123.45444  

$('input').blur(function(e) {
    var $input = $(this),
        matches = $input.val().match(/^\s*\$?([\d,]+)(\.?)(\d*)?\s*$/);
    if (matches) {
        $input.val(matches[1].replace(',', '') + (matches[2] || '') + (matches[3] || '').substring(0, 2));
    } else {
        $input.val('0.00');
    }
});

$('input').keypress(function(e) {
    var charCode = e.which;
    if ((charCode > 31) && !e.altKey && !e.ctrlKey && !e.metaKey) {
        var value = $(this).val(),
            decimalPointIndex = value.indexOf('.');
        if ((charCode >= 48) && (charCode <= 57)) {
            return (decimalPointIndex < 0)
                || ((value.length - (decimalPointIndex + 1)) < 2)
                || (getCaretIndex(this) <= decimalPointIndex);
        }
        return (charCode == 46)
            && (decimalPointIndex < 0)
            && ((value.length - getCaretIndex(this)) <= 2);
    }
    return true;
});

function getCaretIndex(input) {
    if (input.selectionStart !== undefined) {
        return input.selectionStart;
    } else if (document.selection) {
        input.focus();
        var range = document.selection.createRange();
        var selLen = range.duplicate().text.length;
        range.moveStart('character', -input.value.length);
        return range.text.length - selLen;
    }
}