Maxim Sloyko
Maxim Sloyko

Reputation: 15906

Detecting a change in radio button/checkbox state

I need to reliably detect the state change of radio buttons/checkboxes on my page in order to watch if the form was modified or not. Now, this is a completely separate script, I cannot modify anything that controls the form.

Right now, I can see only two ways of doing this:

What am I missing here? Is there a way to reliably detect that checkbox was checked/unchecked?

UPDATE: As you guys pointed out, change event is really fired on checkboxes/radiobuttons, despite the fact that w3schools says it is only for text inputs

However, my problem turned out to be that the values of checkboxes/radiobuttons are set via setAttribute in scripts and in that case the event is not fired.

Is there anything I can do in this case?

Upvotes: 6

Views: 4761

Answers (2)

Maxim Sloyko
Maxim Sloyko

Reputation: 15906

Ok, after some digging, here is what I found out. Note, this is applicable to Firefox, and, probably to Firefox only. Since in this case I was dealing with internal application, this was enough for me.

So, basically, in order to reliably detect changes in checkbox/radiobutton state in Firefox, you need to do two things:

  1. Set up custom Firefox's event handlers CheckboxStateChange and RadioStateChange for checkbox and radiobutton respectively. These events will be fired when the user changes the inputs or when it is modified via script, using setAttribute, however, these events are not fired, when the state is changed in the script, using checked or selected properties of these elements, this is why we need ...
  2. Watch the changes of the checked property using Object.watch

Standard onchange event is no good, since it only fired when user changes the value directly.

Damn, this thing is broken...

If people get interested, I'll post some code.

Upvotes: 0

Taha Jahangir
Taha Jahangir

Reputation: 4902

See: http://www.quirksmode.org/dom/events/change.html.

It says that all major browsers support change event but the IE's implementation is buggy.

IE fires the event when the checkbox or radio is blurred, and not when it is activated. This is a serious bug that requires the user to take another action and prevents a consistent cross-browser interface based on the change event on checkboxes and radios.

I think you can overcome IE's bug with this trick. blur() elements when they focued! (Use something like $('input[type=radio]').focus(function(){$(this).blur();}); in jQuery or use pure javascript)

Upvotes: 2

Related Questions