Oundless
Oundless

Reputation: 5505

Disable keyboard in HTML SELECT tag

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?

Upvotes: 7

Views: 12709

Answers (3)

Oundless
Oundless

Reputation: 5505

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>

Upvotes: 4

xdevel2000
xdevel2000

Reputation: 21364

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;         
   }    
}

Upvotes: 2

user434917
user434917

Reputation:

event.preventDefault()

Upvotes: -1

Related Questions