JSFiddle - React, Tailwind, and code Playground

by Ravindra Athreya

HTML

<input type="text" maxlength="10" id="myInput">

JavaScript

var input = document.getElementById("myInput");

input.onkeypress = function(e) {    e = e || window.event;



//var inputVal = document.getElementById("myInput").value;
//alert(document.getElementById('myInput').selectionStart)

    var charCode = (typeof e.which == "number") ? e.which : e.keyCode;

    // Allow non-printable keys
    if (!charCode || charCode == 8 /* Backspace */ ) {
        return;
    }

    var typedChar = String.fromCharCode(charCode);

    // Allow numeric characters
    if (/\d/.test(typedChar)) {
        return;
    }

    // Allow the minus sign (-) if the user enters it first
    if (document.getElementById('myInput').selectionStart === 0){
    console.log('enter');
    if (typedChar == "-") {
        return;
    }
    }
    
    

    // In all other cases, suppress the event
    return false;
};