Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • onchange event handler, which helps with textboxes, textareas and selects, but is not fired for checkboxes/radiobuttons
  • onclick event handler, which is not reliable, because users often use hotkeys to change the values of these elements.

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?

like image 518
Maxim Sloyko Avatar asked Nov 04 '22 23:11

Maxim Sloyko


1 Answers

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)

like image 162
Taha Jahangir Avatar answered Nov 13 '22 16:11

Taha Jahangir