Javascript to limit input

Posted in Programming  
E-Mail This Post/Page   

Need a way to limit what gets entered into an HTML textbox?

Plug this script into your textbox using...

JavaScript:
  1. onKeyPress="javascript:return limitinput(event, '0123456789', true);"

Variables

  • event - The event that is passed. Just leave is as 'event' when you call it.
  • strList - Either a black list or white list depending on the next variable.
  • bAllow - If false strList acts as a black list. If true strList acts as a white list.
JavaScript:
  1. function limitinput(evt, strList, bAllow)
  2. /*Limits the input to strList. If bAllow is true, then
  3. only allow what is in strList. If bAllow is false,
  4. then do not allow what is in strList.
  5. http://blog.nutt.net
  6. */
  7. {
  8. var charCode = evt.keyCode;
  9. if (charCode==0)
  10. {
  11. charCode = evt.which;
  12. }
  13. var strChar = String.fromCharCode(charCode);
  14. /*controlArray holds the ASCII codes for valid
  15. control commands (BS, CR, LF, etc)*/
  16. var controlArray = Array(0, 8, 9, 10, 13, 27);
  17. var intOut = 0;
  18.  
  19. if (bAllow==true)
  20. {
  21. if (charCode==8 || charCode==9 || charCode==37 || charCode==39 || charCode==46 || charCode==116 || (strList.indexOf(strChar)!=-1))
  22. /*Valid*/
  23. {
  24. return true;
  25. }
  26. else
  27. {
  28. return false;
  29. }
  30. }
  31. else
  32. {
  33. if (charCode==8 || charCode==9 || charCode==37 || charCode==39 | charCode==46 || charCode==116 || (strList.indexOf(strChar)==-1))
  34. {
  35. return true;
  36. }
  37. else
  38. {
  39. return false;
  40. }
  41. }
  42.  
  43. }

More on CSS & Web Buttons
Tips to keep your email address away from spammers
CSS & Web Buttons
Syntax highlighting code in WordPress blogs
Javascript time formatting function

Leave a Comment