JSFiddle - React, Tailwind, and code Playground

by jfriend00

HTML

<label>Digits Only:<input class="integer" /></label><br><br>
<label>Decimal Values Only:<input class="decimal" /></label>

CSS

.advice {padding-left: 15px; color: red;}
label input {margin-left: 10px;}

JavaScript

$(".integer").keypress(function(e) {
    // between 0 and 9
    if (e.which < 48 || e.which > 57) {
        showAdvice(this, "Integer values only");
        return(false);  // stop processing
    }
});

$(".decimal").keypress(function(e) {
    // 46 is a period
    if (e.which != 46 && (e.which < 48 || e.which > 57)) {
        showAdvice(this, "Decimal numbers only");
        return(false);
    }
    if (e.which == 46 && this.value.indexOf(".") != -1) {
        showAdvice(this, "Only one period allowed in decimal numbers");
        return(false);   // only one decimal allowed
    }
});

function showAdvice(obj, msg) {
    $("#singleAdvice").stop(true, false).remove();  // remove any prev msg
    $('<span id="singleAdvice" class="advice">' + msg + '</span>').insertAfter(obj);
    $("#singleAdvice").delay(4000).fadeOut(1500);  // show for 4 seconds, then fade out
}