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">

5
  • 2
    Is there any specific reason why <input type='number'> won't be sufficient? Commented Jul 27, 2022 at 11:18
  • Does this answer your question? Number input type that takes only integers? Commented Jul 27, 2022 at 11:19
  • 1
    and if you wish to know more about input elements in general, the pattern attribute and form validation: developer.mozilla.org/en-US/docs/Web/HTML/Element/input#pattern Commented Jul 27, 2022 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. Commented Jul 27, 2022 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. Commented Jul 27, 2022 at 11:52

1 Answer 1

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"/>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.