0

This question has been asked before back in 2011 Allow only numbers into a input text box but the final code doesn't work in my situation and I did wonder if there was an update scenario.

I am trying to stop all characters other than the numbers 0123456789 from being input.

document.getElementById("text_input").addEventListener("keydown", (eventObject) => {
    
  // Add : after the first 2 chracters
  const length = eventObject.target.value.length;
  const keyCode = eventObject.keyCode;
  
  if (keyCode != 8 && length === 2) {
    eventObject.target.value += ":"
  }
  
  // Stop all characters other than 0123456789 from being input
  const charCode = (typeof eventObject.which == "number") ? eventObject.which : eventObject.keyCode
  
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;

});
<input id="text_input" type="text" name="hours">
Juan-man
  • 436
  • 4
  • 13
  • 2
    Is there any specific reason why `` won't be sufficient? – Martijn Vissers Jul 27 '22 at 11:18
  • Does this answer your question? [Number input type that takes only integers?](https://stackoverflow.com/questions/8808590/number-input-type-that-takes-only-integers) – jsejcksn Jul 27 '22 at 11:19
  • 1
    and if you wish to know more about input elements in general, the pattern attribute and form validation: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#pattern – Diego D Jul 27 '22 at 11:20
  • I can't use number as the input box is a time, unfortunately the software I wam using does not have a time type yet, it'll get added but not sure when. At the moment I need to find a workaround sense why I am using a text box and not time. – Juan-man Jul 27 '22 at 11:52
  • 1
    I would validate values after they were entered, not while typing. Maybe someone wants to copy&paste. Ctrl+V is certainly not a number, but should be allowed. – Peter Krebs Jul 27 '22 at 11:52

1 Answers1

0

document.getElementById("extra7").addEventListener("keydown", (eventObject) => {
    
  const length = eventObject.target.value.length;
  const keyCode = eventObject.keyCode;
  
    
  if (
    eventObject.key.length === 1 && eventObject.key !== '.' && isNaN(eventObject.key) && !eventObject.ctrlKey || 
    eventObject.key === '.' && eventObject.target.value.toString().indexOf('.') > -1
  ) {
    eventObject.preventDefault();
  }

});
<input type="text" class="textfield" value="" id="extra7"/>
Dan
  • 1,565
  • 3
  • 23
  • 43