Link to home
Start Free TrialLog in
Avatar of Whing Dela Cruz
Whing Dela CruzFlag for Anguilla

asked on

IsNumber event

Hi experts, Codes below do not allow any character except the number. However, I need to exclude the (.) or point so that i could write something like this, 10.88. Which part of the code should i chagnge or add to achieve the goal? Thank you!

Js

function isNumber(evt) 
{
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) 
{
alert("Please note that only number is allowed in the box!");
return false;
}
return true;    
}

Open in new window

Avatar of Wilson Net
Wilson Net
Flag of Argentina image

Hi Whing,

for that type of control in my opinion the best is to use RegExp, try using the code below:

function isNumber(e) {
    var key = (document.all) ? e.keyCode : e.which;
    var expression = /[-?\d\.]/; // allow only numbers and point
    var te = String.fromCharCode(key);

    if(expression.test(te)){
        return true;
    }else{
        alert("Please note that only number is allowed in the box!");
        return false;    
    }
}

Open in new window

here

https://jsfiddle.net/4evqxd6h/

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  console.log(charCode);
  if (!((charCode >= 48 && charCode <= 57) || (charCode == 46))) {
    alert("Please note that only number is allowed in the box!");
    return false;
  }
  return true;
}

Open in new window


* it does not detect "." in front at the end or multiples :)
another way of writing above code

function isNumber(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  var charOk = "0123456789.".indexOf(String.fromCharCode(charCode)) > -1;
  console.log(charCode);
  if (!charOk) {
    alert("Please note that only number is allowed in the box!");
    return false;
  }
  return true;
}

Open in new window

This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.