MCDev
MCDev

Reputation: 1

Cross browser code to restrict user input using Javascript

I found this code through Stack Overflow to restrict users from putting numbers in a textbox, however it only works in Chrome and IE. Anyone know of any cross browser code to do this? Note: we've already added the global attribute and it didn't work at all, this was the only one that fully worked in Chrome and IE.

<input type="text" onkeyup="this.value = this.value.replace(/[^a-z]/, '')" />

Upvotes: 0

Views: 96

Answers (1)

Get Off My Lawn
Get Off My Lawn

Reputation: 36311

You want to catch onkeydown that is when the character gets inserted, not on onkeyup. You should also instead of removing the number, just prevent it from getting inserted with event.preventDefault()

<p>
  <input type="text" onkeydown="event.key.match(/\d/) && event.preventDefault()" />
</p>

One thing I would recommend is removing the code from the html and putting it in a function so it is reusable like this:

// Wait till the dom is loaded
document.addEventListener('DOMContentLoaded', function(e) {
  // Add the event to each input that has `data-type="number"`
  document.querySelectorAll('[data-type=number]').forEach(function(input) {
    // Add the event to the input
    input.addEventListener('keydown', number)
  })
})

function number(event) {
  event.key.match(/\d/) && event.preventDefault()
}
<p>
  <input type="text" data-type="number" />
</p>

Upvotes: 1

Related Questions