Textbox that allows values -9999 to 9999

  • A+
Category:Languages

Hello this is what I have right now to allow only numbers and a max of 4 digits. How would I make it so that I can allow a - before the number which would bypass the max 4 digit limit? Currently if I use a - only 3 numbers can be entered after, while I need to make it allow 4 numbers.

// Only Numbers can be Entered function fNumOnly(evt) {   evt = (evt) ? evt : window.event;   var charCode = (evt.which) ? evt.which : evt.keyCode;    if ((charCode >= 48 && charCode <= 57) || charCode == 45) {     return true;   }   return false; }
<input id="txtFahrenheit" type="text" onkeypress="return fNumOnly(event);" maxlength="4" />

 


You can check length of value of input using regex.

function fNumOnly(evt) {   evt = (evt) ? evt : window.event;   var charCode = (evt.which) ? evt.which : evt.keyCode;    if (     ((charCode >= 48 && charCode <= 57) || charCode == 45) &&     evt.target.value.match(/^-?/d{0,3}$/g)   ) {     return true;   }   return false; }
<input id="txtFahrenheit" type="text" onkeypress="return fNumOnly(event);" />

Also you can use type=number and min&max attribute for input instead of checking charCode in function

function fNumOnly(evt) {   evt = (evt) ? evt : window.event;   var charCode = (evt.which) ? evt.which : evt.keyCode;    if (evt.target.value.match(/^-?/d{0,3}$/g))     return true;   return false; }
<input id="txtFahrenheit" type="number" onkeypress="return fNumOnly(event);" min="-9999" max="9999"/>

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: