Jump to content

rejecting arrow keys with onkeydown in Firefox


pnj

Recommended Posts

I want to disable keyboard scrolling for drop down boxes, because people are inadvertently changing the field when they want to scroll the page.

 

The code below works in IE, it does not work in Firefox.  Can you tell me why?  I know the cb() function is returning false, even in Firefox, but the combobox scrolls anyway.  Thoughts?

 

<script>
function cbHandleKeyDown(e) {

  var keynum;
  /* get keystroke number */
  if (window.event) { /* IE */
    keynum = e.keyCode;
  } else if (e.which) { /* Netscape / Opera / Firefox */
    keynum = e.which;
  }

  /* reject arrow keys,home,end,pgup,pgdown - everything that could move the selection. */
  if (keynum > 32 && keynum < 41) {
    return false;
  }

  /* pass other keys through, so it is still possible to navigate with letters*/
  return true;
}
</script>

<select onkeydown="return cbHandleKeyDown(event);"><option>...</option></select>

 

Thanks

Link to comment
Share on other sites

A few things:

 

1)  You are testing the existence of window.event to determine if the browser is IE, which is fine, but then you are assigning the keyCode from e.keyCode and e will be undefined in IE.

 

2)  You are not canceling the default action correctly.

 

3)  I can't remember the details because my example is on a PC at home, but FF, Netscape, and Opera do not set the which property the same, so you may need to do additional testing there.

 

Anyways, try this:

function cbHandleKeyDown(e) {
    e= e || window.event;

  var keynum;
  /* get keystroke number */
  if (window.event) { /* IE */
    keynum = e.keyCode;
  } else if (e.which) { /* Netscape / Opera / Firefox */
    keynum = e.which;
  }

  /* reject arrow keys,home,end,pgup,pgdown - everything that could move the selection. */
  if (keynum > 32 && keynum < 41) {
    if(window.event){
      e.returnValue = false;
    }else{
      e.preventDefault();
    }
    return false;
  }

  /* pass other keys through, so it is still possible to navigate with letters*/
  return true;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.