开发者

Detect changes on disabled field

It seems propertychange events are ignored while a fie开发者_如何学编程ld is in the disabled state. Is there a way to run code when the value changes?

<input id="country" onpropertychange="alert(country.value)" disabled="disabled"/>
<input type="button" onclick="country.value='USA'" value="Go" />


Could you not just add in your event inside the button's onclick attribute after country.value='USA'? For example:

<input id="country" disabled="disabled" />
<input type="button" onclick="country.value='USA'; alert(country.value)" value="Go" />


Yes there is! In short, you'll need to fire the propertychange event yourself when the disabled is set, and to do that you'll need to change the getters and setters on the elements that you want to enable/disable.

Here are a couple of good articles about this technique:

  • MSDN getter/setter article
  • MSDN getter/setter examples

Unfortunately you can't just use the native fireEvent on a disabled event within the setter, because it obeys the disabled state. Therefore we need an external event triggering system. Luckily for us the good folks at jQuery have already done that!

So, with that knowledge I wrote a fireOnDisable jQuery plugin. To use it, simply apply it to the selector eg:

$('#disabled_thing').fireOnDisable();

If you are in a browser that doesn't natively support propertychange events, this plugin will do nothing. It's exclusively for IE8-10. For non-IE browsers (and IE-11) use MutationObservers. For IE7 or lesser, you're screwed, because they don't expose the setter/getter functions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜