1

If I have radio buttons :

<input id="y0" type="radio" name="myRadioBtns" value="a" checked> <label for="y0"></label>
<input id="y1" type="radio" name="myRadioBtns" value="b">  <label for="y1"></label>
<input id="y2" type="radio" name="myRadioBtns" value="c">  <label for="y2"></label>

The radio buttons may have already bound a change event handler like following:

$('input[name='myRadioBtns']').change(function() {
  //EVENT HANDLER
});

I need to check if the radio buttons have already bound with a "change" event handler or not.

My question is How to check if the radio buttons has already bound with a "change" event handler?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Mellon
  • 37,586
  • 78
  • 186
  • 264
  • http://stackoverflow.com/questions/1515069/jquery-check-if-event-exists-on-element should help. – Loktar Sep 07 '11 at 13:18
  • http://stackoverflow.com/questions/1236067/test-if-event-handler-is-bound-to-an-element-in-jquery – Samich Sep 07 '11 at 13:19

3 Answers3

2

You can get bound events with:

.data('events')
Teneff
  • 30,564
  • 13
  • 72
  • 103
mike
  • 648
  • 5
  • 13
  • Hi, thank you, I come with another problem which is here http://stackoverflow.com/questions/7334947/how-to-make-sure-only-one-event-handler-get-called-when-select-radio-buttons-very – Mellon Sep 07 '11 at 13:49
2

If you want to test whether a change event has already been bound before you bind another one, use this:

var $el = $('input[name='myRadioBtns']');

if( ! ($el.data('events') && $el.data('events').change) ) {

   $el.change(function() {
       //EVENT HANDLER
   });
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292
  • Hi, thank you, I come with another problem which is here http://stackoverflow.com/questions/7334947/how-to-make-sure-only-one-event-handler-get-called-when-select-radio-buttons-very – Mellon Sep 07 '11 at 13:49
0

Also, you can bind multiple namespaced change events that each do different things. For example if you were writing a jQuery plugin that needs to bind events to elements, but not remove any existing events that might already be set on the page.

Whenever I'm writing a jQuery plugin I make sure all events are bound like this:

    $(":checkbox").on("change.myNamespace", function(){
        //Do Stuff - this won't replace existing change events on checkboxes!
    });
Chris Barr
  • 29,851
  • 23
  • 95
  • 135