0

I want to create TextField it allows only numbers.For this I written the following code but it's not working.

script code:

 function numberTextField(){
var keyAsciiValue=event.keyCode||event.which;
console.log(keyAsciiValue);
if (keyAsciiValue>=48&&keyAsciiValue<=57) {
    console.log("This is Number");
    return true;
}else{
    console.log("This is Not a Number");
    return false;
};
} 

html code:

<input type="text" onkeyup="numberTextField()" placeholder="NoOfRows" id="fieldsCount2"/>

can anyone help me.

Thanks.

user2873816
  • 179
  • 1
  • 5
  • 16

2 Answers2

0
function numberTextField(evt)
{
   var charCode = (evt.which) ? evt.which : event.keyCode
   if (charCode > 31 && (charCode < 48 || charCode > 57))
   {
         console.log("This is Not a Number");
         return false;
   }
   else
   {
          console.log("This is a Number");
          return true;
   }         


} 

and the HTML

<input type="text" onkeypress="return numberTextField(event)" placeholder="NoOfRows" id="fieldsCount2"/>
Dilantha
  • 1,552
  • 2
  • 30
  • 46
0

updated code:

<input type="text" value="" onkeypress="this.value = this.value.replace(/[^0-9]$/,'')"  onkeyup="this.value = this.value.replace(/[^0-9]$/,'')" placeholder="NoOfRows" id="fieldsCount2"/>
Joke_Sense10
  • 5,341
  • 2
  • 18
  • 22