Disable keyboard in HTML SELECT tag

人盡茶涼 提交于 2020-01-03 18:57:20

问题


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?


回答1:


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



回答2:


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>



回答3:


event.preventDefault()


来源:https://stackoverflow.com/questions/1227146/disable-keyboard-in-html-select-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!