Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Textbox that allows values -9999 to 9999

How would I make it so that I can allow a ‘-‘ (negative sign) before the number which would bypass the max 4 digit limit?

Currently, if I use a ‘-‘, only 3 digits can be entered, while I need it to allow 4 digits.

// 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" />
like image 988
Shadow Zero Avatar asked Nov 19 '25 11:11

Shadow Zero


2 Answers

Why not use <input type="number"> with min and max values? For example:

input:valid {
  border-color: green;
}

input:invalid {
  border-color: red;
}
<div>Enter a number between -9999 and 9999 (green for valid entry, red for invalid entry)</div>
<input type="number" name="num" min="-9999" max="9999" required>
like image 186
benvc Avatar answered Nov 21 '25 02:11

benvc


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"/>
like image 44
Mohammad Avatar answered Nov 21 '25 00:11

Mohammad