4

I'm using javascript to simulate a disabled select element. I can't actually disable it as the .net validators fail, but that's another story.

I have the following function:

function preventFocus(e) {
  if ($(this).hasClass("disabled")) {
    e.preventDefault();
    this.blur();
  }
}

That is called here:

$("#ProvinceID").toggleClass("disabled").bind('focus click dblclick', preventFocus);

Double-clicking the select box in IE still seems to allow the items to be displayed and selected. I tried the IE developer toolbar, and the e.type is showing up as focus and dblclick. Is this an IE bug, or do I need to catch some other event? I also tried focusin.

Thanks!

ScottE
  • 21,027
  • 18
  • 91
  • 129

2 Answers2

1

This is 4 years late but I just discovered there is in fact a way to get IE ≤ 8 to do what e.preventDefault() on mousedown does in other browsers (which prevents selection and prevents focus): set the unselectable attribute! http://jsbin.com/yagekiji/1

Note that unlike the workarounds always suggested, which always boil down to setTimeout(function() { thingIDidntWantFocusStolenFrom.focus(); }), this prevents focus from ever being stolen by the mousedown target in the first place!

What's funny about unselectable is that it isn't inherited, so it's often overlooked in favor of the selectstart event (which bubbles, and e.preventDefault() on which prevents selection but doesn't prevent focus), or set on every descendant element with a tree-traversal (like the StackOverflow answer that first clued me in that this might be possible, or Tim Down's series of nearly identical answers), but you can actually just set it on event.target on mousedown.

(Also, jQuery ticket: http://bugs.jquery.com/ticket/10345)

Community
  • 1
  • 1
Han Seoul-Oh
  • 1,140
  • 1
  • 9
  • 17
0

I don't know if it's just a typo, but you should use e.preventDefault(); looks like you were missing the parenthesis.

Mike Sherov
  • 12,634
  • 7
  • 38
  • 62