Link to home
Start Free TrialLog in
Avatar of BR
BRFlag for Türkiye

asked on

I'm looking for a javascript that only allows to write numbers into my text field,

I'm looking for a javascript that only allows to write numbers into my text field,
if anybody try to write a letter the javascript should warn the user.
please write a number not letter,
Avatar of coolersport
coolersport
Flag of Australia image

Try this one that I found on the Internet:
<HTML>
   <HEAD>
   <SCRIPT language=Javascript>
      <!--
      function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
 
         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar">
   </BODY>
</HTML>

Open in new window

Avatar of BR

ASKER

It's a very good function,
however, I need if somebody writes a letter, it should give a warning (alert) that the user should write numbers not letters.
can you help me out pls?
ASKER CERTIFIED SOLUTION
Avatar of coolersport
coolersport
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of BR

ASKER

You are perfect :)
>>however, I need if somebody writes a letter, it should give a warning

How very annoying - if a single mis-typed letter creates a popup and requires a click to dismiss, you are going to work your Poor Users into a fine fettle.
Avatar of BR

ASKER

Dear Badotz,
you are right actually,
what do you recomend?
should I open a new question for your comment?
Not necessary.

One wonders why only numbers are allowed...and wouldn't it be better to wait for the user to finish typing before you check for compliance? I mean, you could strip out the non-numerics *afterwards* and THEN alert the Poor User why you changed her input.
Try this one as a bonus :D. That way it won't interfere with user activity.

Cheers,
Tien
  <HEAD>
   <SCRIPT language=Javascript>
      <!--
      var warning = null;
      function isNumberKey(evt)
      {
         if (!warning) warning = document.getElementById('warning');
         var charCode = (evt.which) ? evt.which : event.keyCode
         if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            warning.innerHTML = 'Only numbers are allowed.';
            return false;
         }
         warning.innerHTML = '';
         return true;
      }
      //-->
   </SCRIPT>
   </HEAD>
   <BODY>
      <INPUT id="txtChar" onkeypress="return isNumberKey(event)" type="text" name="txtChar"><span style="color:red" id="warning"></span>
   </BODY>
</HTML>

Open in new window