PK Kulhari
PK Kulhari

Reputation: 43

Check for numeric value into input field using JS

I want to make sure that users enter only numeric value into the input field. I tried the following but its not working. Don't want to set attribute like onkeypress="return isNumeric(event, value) manually."

// Event listeners
saleForm.querySelectorAll('input.only_numeric').forEach(input => {
    input.addEventListener('keypress', isNumeric);
});

// Functions
function isNumeric(event) {
    const value = this.value;
    const unicode = event.charCode ? event.charCode : event.keyCode;

    if (value.indexOf('.') != -1) {
        if (unicode == 46) return false;
    }

    if (unicode != 46) {
        if ((unicode < 48 || unicode > 57) && unicode != 46) return false;
    }
}
 <input type="text" id="bill-cust-mobile" tabindex="4" class="only_numeric">

Upvotes: 0

Views: 194

Answers (3)

Yevhenii Shlapak
Yevhenii Shlapak

Reputation: 786

Try also isNan:

//Runs code if val is numeric
if(!isNan(val){...}

Upvotes: 0

jcHernande2
jcHernande2

Reputation: 291

You can use the conditional with operation number%1

Example:

function isNumeric(event) {
    const value = this.value;
    const unicode = event.charCode ? event.charCode : event.keyCode;
    
    return !isNaN(value) && value % 1 == 0;
    
}

Upvotes: 0

Yura Shtefanko
Yura Shtefanko

Reputation: 167

Set: <input type="number">

Upvotes: 2

Related Questions