samedi 30 janvier 2021

How can I evaluate an HTML input element for any possible changes and reshape the value?

I have an HTML input element for positive integer numbers. I need to evaluate this input field and ensure that only proper values are inserted.

HTML:

<input id="exampleInput" type="number"
      value="0" min="0" step="1" maxlength="5" onkeypress="exampleFunction(event, this)">

JS:

function exampleFunction(event, element){

  // If event is not backspace and Not a Number
  if(event.which != 8){

    //If the event is Not a Number
    if(isNaN(String.fromCharCode(event.which))){

      // Cancels the event
      event.preventDefault();
    }
    //If the length reached the limit
    else{

      var value = document.getElementById(element.id).value;
      var maxLength = document.getElementById(element.id).maxLength;
      var valueLength = document.getElementById(element.id).value.length;

      if(valueLength >= maxLength){

        // Cancels the event
        event.preventDefault();
      }else{

        // Convert the value to a number and back to string. This means leading 0 will be gone.
        document.getElementById(element.id).value = Number(value);
      }
    }
  }

};

purposes:

  • default value is 0
  • only numbers shall be accepted
    • no decimal value .,
    • no other characters +-e
  • the input can come from:
    • typing
    • copy
  • backspace and delete can also modify the value
  • length of input shall also be limited for 5 character length
  • leading 0 shall be eliminated after a proper new value

Problems:

  • the default value is 0 and leading zeros are not immediately deleted, only after the second number is typed
  • with ctrl+v .,+-e characters can be inserted

Question: Is any better solution for my purposes? If it is jQuery related, it is also acceptable.

Maybe I am not using the proper event. I tried also to handle the input event but it is not possible to evaluate the input text. I am not sure if I make this too complicated, or the solution would be much more complex than I think.




Aucun commentaire:

Enregistrer un commentaire