tags:

views:

59

answers:

2
<script>
$("input[name='my_radio_button']").change(function(){
    if ($("input[@name='my_radio_button']:checked").val() == 'ONE'){
                do_this_stuff(); 
    } else { do_other_stuff(); }
});
</script>

<input type="radio" name="my_radio_button1" id="radio1" value="ONE" checked />
<input type="radio" name="my_radio_button2" id="radio2" value="TWO" />

(assume complete HTML and the script firing when all is ready)

The change event seems to fire when clicking to select a radio option, but not when the selection is changed with keyboard. Can anything be done about this?

edit - makes no difference if I use bind or live -- is this just a bug?

To clarify, the event does not fire even after focus is lost.

edit 2 - nobody knows the reason for this?

A: 

Unfortunately, radio buttons don't fire change events when changed with the keyboard, until you lose focus.

If you want to work around this problem, you can always set up a timer that monitors the state, and dispatches an event when it changes. Something like (pseudocode):

var monitorRadio = function(radio)
{
   var state = $("input[@name='']:checked").val();
   $(radio).data("state", state);
   var func = function()
   {
     var state = $("input[@name='']:checked").val();
     if (state != $(radio).data("state"))
     {
       $(radio).data("state", state);
       // dispatch the change event
       $(radio).change();
     }
     setTimeout(100, func());
   };   


   func();
}
Scott S
Thanks for the workaround, but my code is not working even *after* the radio buttons lose focus. I'll tab over to another field and jquery just ignores the change entirely. The select box, for example, works properly when changed and focus is lost.
Greg
A: 

I'm not having much luck getting the radio button to change it's state with the arrow keys in my jsfiddle, so here's a blind answer:

Use .keypress() The same rule about not changing until loosing focus applies to select boxes, and I've successfully used .keypress() there

http://api.jquery.com/keypress/

SooDesuNe