Disable keyboard in HTML SELECT tag

10,097

Solution 1

Someone left me the correct answer and then removed it for some reason, so here it is:

function IgnoreAlpha(e) {
  if (!e) {
    e = window.event;
  }
  if (e.keyCode >= 65 && e.keyCode <= 90) // A to Z
  {
    e.returnValue = false;
    e.cancel = true;
  }
}
<p>
  <select id="MySelect" name="MySelect" onkeydown="IgnoreAlpha(event);">
    <option selected="selected " value=" " />
    <option value="A ">A</option>
    <option value="B ">B</option>
    <option value="C ">C</option>
  </select>
</p>

Solution 2

In a cross-browser way assuming that the event object has been properly initialized:

function disableKey(e)
{
   var ev = e ? e : window.event;

   if(ev)
   {
       if(ev.preventDefault)
          ev.preventDefault();
       else
         ev.returnValue = false;         
   }    
}
Share:
10,097
Oundless
Author by

Oundless

Ageing web developer

Updated on June 16, 2022

Comments

  • Oundless
    Oundless almost 2 years

    I want to disable the keyboard for an HTML SELECT tag so the user can only use a mouse to select the options.

    I've tried event.cancelBubble=true on the onkeydown, onkeyup and onkeypress events with no luck.

    Any ideas?