Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

313
Views
How do I allow only character input (a-z,A-Z) in my input field in javascript?

I want to be able to type only alphabets in my input field, not numbers. I've tried this code but it doesn't work:

document.getElementById("input").addEventListener("keypress",function(event){
        return (event.code=="KeyA"||event.code=="KeyB"||event.code=="KeyC"||event.code=="KeyD"||
        event.code=="KeyE"||event.code=="KeyF"||event.code=="KeyG"||event.code=="KeyH"||event.code=="KeyI"||
        event.code=="KeyJ"||event.code=="KeyK"||event.code=="KeyL"||event.code=="KeyM"||event.code=="KeyN"||
        event.code=="KeyO"||event.code=="KeyP"||event.code=="KeyQ"||event.code=="KeyR"||event.code=="KeyS"||
        event.code=="KeyT"||event.code=="KeyU"||event.code=="KeyV"||event.code=="KeyW"||event.code=="KeyX"||
        event.code=="KeyY"||event.code=="KeyZ");         
      })

Please help me.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Simplest way to do that is to use HTML pattern Attribute

For example:

<input type="text" id="country_code" name="country_code"
  pattern="[A-Za-z]{3}" title="Three letter country code">

Or with key events

about 4 years ago · Juan Pablo Isaza Report

0

Using event.preventDefault() method can prevent running default task of events. Just check if event.key is not in your allowed list, run event.preventDefault(). In following code I used event.key.toLowerCase() that cause accepting both d and D.

document.getElementById("input").addEventListener("keypress",function(event){
    if("abcdefghijklmnopqrstuvwxyz".indexOf(event.key.toLowerCase()) < 0)
        event.preventDefault();
})
<input id="input" type="text">

about 4 years ago · Juan Pablo Isaza Report

0

You can try this way

<input type="text" name="name" id="event" onkeypress="return alphabhets(event);" />
function alphabhets(event) {
  const key = event.keyCode;
  return /[a-z]/i.test(event.key);
};
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!