Link to home
Start Free TrialLog in
Avatar of Xavior2K3
Xavior2K3

asked on

Textbox that only allows integers

Hi,

I need some javascript jcode that can restrict input to a textbox to only allow integers to be entered.  It is prefferable that it checks the input when they are typing it in as opposed to when they leave the textbox.

Thanks,
Michael
ASKER CERTIFIED SOLUTION
Avatar of Diablo84
Diablo84

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 CrYpTiC_MauleR
CrYpTiC_MauleR

<script type='text/javascript'>
function RestrictUserInput(elem) {
    if (/[^\d]/g.test(elem.value))
       elem.value = elem.value.replace(/[^\d]/g, '');
}
</script>
<form>
<input name='field' onkeyup='RestrictUserInput(this);' />
</form>

This will auto-remove any invalid character as they type only allowing integers.
Diablo,
your code doesnt swork in Mozilla and Netscape
document.captureEvents() must be used then.
SOLUTION
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
SOLUTION
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
Sorry jaysoloman, seems we posted at the same time.

Basically the same code except yours clears the entire field if the value entered is not a number, a bit annoying if you've already gone 8 numbers and have to retype them.

Regards...
<input type="text" name="text1" onkeyup="this.value=this.value.replace(/\D/,'')">
Cool Gwyn, that's about as simple as it gets!

Regards...
thx :-)

this stops the paste as well

<input type="text" name="text1" onkeyup="this.value=this.value.replace(/\D/,'')" onchange="this.value=this.value.replace(/\D/g,'')">
slightly better

<input type="text" name="text1" onkeyup="this.value=this.value.replace(/\D/g,'')" onchange="this.value=this.value.replace(/\D/g,'')">
Avatar of Xavior2K3

ASKER

thanks for all the great responses, all i need to do now is to find out how i can only allow one minus sign and make sure that its the first charactor in the text.

Thanks again.
   This allows only integers and a minus at the beginning only. To stop people pasting in non-digits you must check off the onblur as well

<script>
function intCheck(val){
 val=val.replace(/[^-\d]/g,'')
 val=val.replace(/(\d)-/g,'$1')
 return val
}
</script>


<input type="text" name="text1" onkeyup="this.value=intCheck(this.value)"
onchange="this.value=intCheck(this.value)">
sorry off the onchange not onblur
Just curious Gwyn, in your "slightly better" post, you have:

>>   onkeyup="this.value=this.value.replace(/\D/g,'')"   <<

Why would this be slightly better? Having "this.value.replace(/\D/,'')" happen "onkeyup" would eliminate the need to replace all occurrences because there would never be more than one occurrence at a time , no? Having it replace all occurrences with the "onchange" for Paste makes sense though.

Regards...
not if they pasted some letters in and then typed numbers, they would be cleared on the onchange though.
Hi, can someone explain to me how the replace method works?  Im not sure what the /\D/g means.
The "\D" matches any nondigit. The "g" means "ever occurrence of".

So, value.replace(/\D/g,'') means it will find ever nondigit character "\D" and replace all occurrences "g" with nothing '' (two single quotes with nothing in between).

Here's a site you may wish to check out:
http://www.regexlib.com/CheatSheet.htm
\D identifies non-digits and the g means global ie do it to all them, so /\D/g means all non digits and replace(/\D/g,'') means replace all non digits with nothing, ie remove them.
Typo -> "ever occurrence of" == "every occurrence of"
Hiya,

Ive been having some problems but think ive got it.

I need to know how to catch errors using the parseInt function in javascript.  So if i run parseInt("---6") i can catch the error.  It keeps returning NaN but i need to beable to test it and do something else if the parse fails.
SOLUTION
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
Hello,

I have finished creating my control, i have used bits and pieces from this topic and here is the correct solution that work to my satisfaction.  Sorry if its been a while but i will explain it as i needed a completely error free input method where i dont have to perform any checks as i know the data will be correct when i use it:

Attributes on my textbox:

       ... onchange="finalCheck()" onkeypress="return maskKeyPress(event)" ...

Javascript:

     function maskKeyPress(objEvent)
     {
       var iKeyCode;      
       iKeyCode = objEvent.keyCode;              

       // only allow numbers and the minus keys to be entered
       if (iKeyCode>=48 && iKeyCode<=57) {
          return true;
       }
       else if (iKeyCode == 45) {
          return true;

       }
       else
          return false;
     }

     function finalCheck()
     {
                // This final check occurs when then leave the textbox, it ensures that it is an integer
      if (isNaN(parseInt(window.event.srcElement.value))) {
            window.event.srcElement.value = "";

        } else {
            window.event.srcElement.value = parseInt(window.event.srcElement.value);
        }
     }

This works perfectly and i would like to thank everyone for there help and i will split the points.  Thanks again.
Between you and me the code you are using is dreadful.
.....it does not work in Netscape or Mozilla either.
What code does Netscape or Mozilla not like?  I would love to hear your suggestions, as long as you drop the attitude, I don’t think anyone appreciates it!
I am just being honest, I truly believe what I have said.
I am not doubting your honesty, i am asking you, why doesnt the code work in netscape or mozilla?  Can you tell me specificly what code cant Netscape or mozilla interpret?
Lol, have you tried your code???? Try it, now before you call my code dreadful, use your code and enter a number.  Now move your cursor around the text to change a number in the middle......it jumps to the end!!  This will be unacceptable to any client.  My code doesnt do this,  that is why i have used my code, i am trying to create software that is user friendly and precise.

I do thank you for pointing out the browser incompatibility, i will check this out, but my priority is IE and other browsers can wait until my software is complete and functioning on IE, which is the main browser my client uses.
virtually all of it
Ok, i will look at it,  but i urge you to look at the code you gave me.  It is simple dreadful to use your wise words.  I apolagise for any hard feelings but i hope you see the flaws in the code you gave me.

Thanks to everyone else that helped me with this problem.

Regards,
Michael
The code is easily for fine tuned. Use what you wish, you have a lot to learn.
I intend not to get caught into an argument.  I would finally like to tell you that your code needs to be revised completely.  Your method of resetting the value of the textbox every keyup event will always cause the cursor to move to the end.  Therefore, my method, thanks to everyone else does not suffer from this significant problem.

I feel that you have a problem with me and wish to take it no further.  If you cannot accept the flaw in your code then i feel you have a lot to learn.

Thanks again to everyone else that helped.
unbelievable.
 If you had presented your requirements in detail then code could have been developed and fined tuned to exactly what you wanted. There are people here who are as good at JS as it is possible to get. For your 500pts you would have got a first class professional cross browser compatible control. Your first visit to the JS TA has not been a good one.
I dont think you understand.  Yes i am aware that i did not ask for cross browser code, but maybe that is because, as i stated earlier, i do not need this compatilibily as of now.  So for my 500pts i got all the help i needed from everyone that helped in this question, i did however also get something i didnt ask for.  I just wish you would let go,  you could have helped many people in the time you spent bickering here,  I have moved on now, my software is functioning just how i wanted it to.  Maybe not over many browsers (or so i have been told), but i will cross that bridge when i get to it.

Now, to try and get back onto the right path, would it be possible for you to show me how you would tackle this problem, and fine tune your example?  I am very grateful for your input and as it happens that i found that it needs some work.  Could you use your expertise and give me some code that is cross-platform and that doesnt have the usability issue or can we leave this topic and call it quits.

If you have a method better than mine then i am more that happy to use it.  But for now, i hope you can see, as can everyone else here, that i have to use my code because the example you gave me simply cant be used because absolutly no user could possibly tolerate it.
      You still do not get it.  I never recall saying why did you not pick mine as as? After trying the codes and commenting you could have had a first class piece of code, it is called development. And just a few iterations can make a huge difference. There is no single way of writing these controls and a lot depends on the preferences of the asker. Especially if you want to go off the key event, that's why most validation is done onchange or onsubmit. Key event validation is very messy. For instance with mine the next iteration might be

<script>
function intCheck(obj){
val= obj.value
if (isNaN(val)){
 val=val.replace(/[^-\d]/g,'')
 val=val.replace(/(\d)-/g,'$1')
 obj.value=val
}
}
</script>

<input type="text" name="text1" onkeyup="intCheck(this)" onchange="intCheck(this)">

there might be something you do not like about that so we work on in and possibly even go to a completely different idea.
Possibly this, which is is a good piece of code but probably is not perfect either

<script>
 ie = (document.all)? true:false
 function keyPress(e) {
  if (ie) var Key = event.keyCode                    
    else   var Key = e.which
  ch =String.fromCharCode(Key )

  if (ch=='-' && /\-/.test(document.getElementById('txt').value) ) return false
  if (/[\d\-]/.test(ch) || Key<=13) return true
    else return false
 }

 function init(){
  document.getElementById('txt').onkeypress = keyPress
  if (!ie) document.captureEvents(Event.KEYPRESS)
 }
</script>
</head>

<body onload='init()'>
<form action='http://abc.com'>
   <input type='text' name='txt' id='txt' onblur="this.value=this.value.replace(/[^\d\-]/g,'').replace(/(\d)\-/,'$1')">
   <input type='submit'>
</form>
</body>

have your tested the control thoroughly? does the form submit for instance?  
I just do not like to see bad workmanship.
Hi,

Could you run me through a few things?  I dont understand this test condition:

             /\-/.test(document.getElementById('txt').value)  

and also the following line    

             /[\d\-]/.test(ch)

Im not quite sure what they are doing.  Also i was wondering how i can find out what does and doesnt work with IE, Netscape etc...  Im not sure what type of problems occur.  As you can tell im not a Javascript pro, but im creating a ASP.NET front end and need some client side scripting to make my validation more user friendly.  Are there any resources or books that shows you what you can and cant do on the major browsers in terms of javascript?  Is it wise to install multiple browsers on my development machine and test each section with each one?

Thanks,
Michael
Gwyn, would there be a way of making sure that the indexOf('-') is the first character of the value, and if not, replace it as well?
Yep that is one of the main problems and what makes this a hard problem, just integers is easy. I think this does it all , I will discuss it later. Busy at the moment

<script>
ie = (document.all)? true:false
function check(obj){
 if (isNaN(obj.value)){
 obj.value=obj.value.replace(/(\d)\-/g,'$1')
 obj.value=obj.value.replace(/[^\d\-]/g,'')
 obj.focus()
 }
}

function keyPress(e) {
setTimeout("check(document.getElementById('txt'))",0)
if (ie) var Key = event.keyCode
else var Key = e.which
ch =String.fromCharCode(Key )

if (ch=='-' && /\-/.test(document.getElementById('txt').value) ) return false
if (/[\d\-]/.test(ch) || Key<=13) return true
else return false
}

function init(){
document.getElementById('txt').onkeypress = keyPress
if (!ie) document.captureEvents(Event.KEYPRESS)
}
</script>

<body onload="init()">
<form action="http://google.com">
  <p><input type="text" name="txt" id="txt" onblur="check(this)">
     <input type="submit"> </p>
</form>
</body>
......taking the - out is not difficult but stopping the cursor moving gets messy.
..and here is the code for multiple instances

<script>
ie = (document.all)? true:false
function check(obj){
 if (isNaN(obj.value)){
  obj.value=obj.value.replace(/(\d)\-/g,'$1')
  obj.value=obj.value.replace(/[^\d\-]/g,'')
  obj.focus()
 }
}

function keyPress(e) {
obj=document.obj
setTimeout("check(obj)",0)

if (ie) var Key = event.keyCode
else var Key = e.which
ch =String.fromCharCode(Key )

if (ch=='-' && /\-/.test(obj.value) ) return false
if (/[\d\-]/.test(ch) || Key<=13) return true
else return false
}

function init(){
document.getElementById('txt1').onkeypress = keyPress
document.getElementById('txt2').onkeypress = keyPress
if (!ie) document.captureEvents(Event.KEYPRESS)
}
</script>

<body onload="init()">

<form action="http://google.com">
 <input type="text" name="txt1" id="txt1" onfocus="document.obj=this" onblur="check(this);document.obj=0">
 <input type="text" name="txt2" id="txt2" onfocus="document.obj=this" onblur="check(this);document.obj=0"><p>
 <input type="text" name="txt3" id="txt3">
 <input type="submit">
</form>
</body>

Comments

(a)  /\-/.test(document.getElementById('txt').value)   this tests fo a  -  in the string
 
(b) /[\d\-]/.test(ch)   tests for ch being a digit or a  -

(c)  /[^\d\-]/.test(ch)   tests for ch not being a digit or a -

(d) obj.value=obj.value.replace(/(\d)\-/g,'$1')  replaces a digit followed by a - with just the digit

(e) The NS code is the mainly with the key detection ie thses lines

ie = (document.all)? true:false        // NS does not have an object called document.all so ie is true for if browser=IE false otherwise
if (ie) var Key = event.keyCode                    
    else   var Key = e.which

and this line

 if (!ie) document.captureEvents(Event.KEYPRESS)

which instructs NS to capture key events

(f) What versions you program for varies from person to person and what the app. is. I usually just test on current NS and IE, if people can not be bothered to download the latest versions then that is their problem

(g) The differences between NS7 and IE6 are not large relative to differences before. Key and mouse capture is one main differences. There are sites giving lists.  
 

..(h) I can paste nondigits into amongst the digits for the code you are presently using with odd results on blur and I can type as many - as I wish, although they are cleaned out on blur sometimes competely balnking the field. If the onblur is caused by a form submit then these odd results go to the server.  If your number starts with a zero than on blur odd things happen, and return will not submit the form if the field is in focus.
I have spotted a problem with mine, paste in nondigits and keep the field in focus and press return sends the nondigits to the sever, insert the line  if (Key==13) check(obj) after ch =String.fromCharCode(Key). This illustrates the problems of on key press validation The subcases are endless. Thats all for now.
Hi,  I have worked on the integer textbox and have found a solution i am happy with now!  Thanks to everyone for the help.  Thanks to Gwyn for your help too,  no hard feelings mate.  I found that you can add a handler for the onkeydown as well as onkeypress.  This keydown event gets processed before the form can submit so the problem addressed by Gwyn on the last post should be fixed.  If you can spot anything i cant then please let me know. Heres the code:

<html>
<head></head>
<body>

<form name="myForm" onsubmit="return complete()">
<input type="Text" id="txt1" text="" style="text-align: center;" onblur="check(this)" />
<input type="submit" />
</form>

</body>
</html>

<script language="Javascript" type="text/javascript">
<!-- Hide from old browsers

document.myForm.txt1.onkeypress = keyHit
document.myForm.txt1.onkeydown = otherCheck
document.myForm.txt1.focus()
document.myForm.txt1.select()

if (document.layers) {
   document.captureEvents(Event.KEYDOWN)
}

function check(obj) {
   // get rid of anything but numbers and -
   if (isNaN(obj.value)) {
      obj.value = obj.value.replace(/[^\d\-]/g, "")
      obj.value = obj.value.replace(/(\d)\-/g, "$1")
      obj.focus()
   }
}

function keyHit(evt) {
   setTimeout("check(document.myForm.txt1)",0)

   // get key pressed
   if (evt) {
      thisKey = evt.which // Netscape
   } else {
      thisKey = window.event.keyCode // IE
   }
   // only allow numbers or minus or enter
   if ((thisKey >= 48 && thisKey <= 57) || thisKey == 13) {
      return true
   } else if (thisKey == 45 && /\-/.test(document.myForm.txt1.value) != true) {
      return true
   } else {
      // Other illegal charactors
      return false
   }
}

function otherCheck(evt) {
   // get key pressed
   if (evt) {
      thisKey = evt.which // Netscape
   } else {
      thisKey = window.event.keyCode // IE
   }

   if (thisKey == 13) {
      check(document.myForm.txt1)
   }
}

function complete() {
   alert(document.myForm.txt1.value)
   return false
}

// End hide -->
</script>
   The field must have a name field else nothing gets sent, when testing always send to a server. I use google which sends me me to the error page but tells me the values that got submitted, (getting google home page => nothing got sent). Otherwise all looks good.


<form name="myForm" action="http://google.com">
  <input type="Text" id="txt1" text style="text-align: center;" onblur="check(this)" name="txt1" /><p>
  <input type="submit" />
</form>
Hiya,

Yea sorry usually would have a name but been working with ASP.NET and used to using id!  I have modified the code as after liaising with the client it has been decided that, if an incorrect value is pasted into the field, it should just change to empty and not try and extract all the digits to construct a number which is likley to be of no significance.  Ill post the code if you want to see it.

I have also done a decimal text box, think the code is good.  Would you care to take a look?  Ill create another topic for it if you want so you can comment on it for points.  Then i need to create a Date text box and im done!!!

Cheers,
Michael
Michael,

Did you end up with cross-browser compatibility? I'd be interested in your end results if you still have them. I was trying to do this for both MS and IE about 5 years ago, but had lots of trouble with NS.

Appreciate your feedback.

Adam Finster