Search code examples
javascripthtmlinputhighlight

Highlighted input text wont update on key press


I am having an issue when the user highlights their entire input in a tag and then on keypress of a number to update the selected input, the input won't update if the max input size was reached (this only happens when the user highlights the entire input value). In the case of my code below the input type is a number with the range 0-999 and the max input size equals 3. What might be the cause of this issue?

input.js:

table.rows[2].cells[1].innerHTML = "<input type=number id=input name=number min=0 max=999 value=>";

document.getElementById("input").addEventListener("input", processInput);

document.getElementById("input").onkeypress = function() {
   if (this.value.length == 3) {
      return false;
   } 
   if (event.charCode == 46 || event.charCode == 45) {
      event.preventDefault();
   }
};

Solution

  • looks like your problem is the first if statement in that onkeypress handler -- if you have 3 characters, no processing occurs. Sadly, setting a max value on a number input doesn't stop the user from typing in a larger number (at least, not on Firefox), neither does setting a maxlength property seem to do the trick. However, I've put together some javascript which provides a nearly-natural response:

    • typing extra characters: they are fleetingly shown, but then trimmed off
    • reducing less than zero: should clamp to zero
    • back-spacing should allow emptying the field.

    here goes:

    <script type="text/javascript">
    var input = document.querySelector("#input");
    var min = parseInt(input.min);
    var max = parseInt(input.max);
    
    input.onkeypress = function(ev) {
      // I assume the OP has a good reason for ignoring
      // - and .
      if (ev.charCode == 46 || ev.charCode == 45) {
         ev.preventDefault();
         return;
      }
    };
    input.onkeyup = function(ev) {
      var current = parseInt(input.value);
      if (current == "") {
        return;
      }
      input.value = clamp(current);
    }
    function clamp(value) {
      if (isNaN(value)) {
        return "";
      }
      if (value >= min && value <= max) {
        return value;
      }
      if (value > max) {
        var str = value.toString();
        return str.substr(0, (max + "").length);
      }
      return min;
    }
    </script>
    

    And of course this script should only be found after the input, since it assumes the input exists. You may also need to modify this to suit the needs of multiple inputs as I've stored variables like the input and it's min/max in global variables.