Brendan Vogt
Brendan Vogt

Reputation: 26018

Determining when a radio button selection has changed with YUI3

I am using YUI3 and Internet Explorer 8 and Firefox. I am trying to determine when a radio button has changed selection.

My HTML:

<div id="test">
     <input name="test1" value="a" type="radio">
     <input name="test1" value="b" type="radio">
     <input name="test1" value="c" type="radio">
</div>

My JavaScript:

YUI().use('event', 'node', function (Y) {
     Y.one('input[name=test1]').on('change', function (e) {
          alert('changed');
     });
});

This doesn't work because the page loads nothing is selected in the radio button group. When I select the first item nothing happens, no alert pops up. When I click the second button then it pops up. How do I determine when a radio button selection has changed?

Also how do I get the value of the selected radio button, I think there are IE issues? This bombs out:

var value = Y.one('input[name=test1]:checked').get('value');
alert(value);

And this bring back nothing:

var value = Y.all('input[name=test1]:checked').get('value');
alert(value);

Upvotes: 1

Views: 1759

Answers (1)

juandopazo
juandopazo

Reputation: 6329

You can use event delegation to listen to the "click" event. If you don't know what event delegation is, check out this short intro. The change event has issues in older browsers so stick to the click event. All you need to do is get the parent element with Y.one and set up a delegation listener:

YUI().use('node', function (Y) {
  Y.one('#test').delegate('click', function (e) {
    alert(e.target.get('value'));
  }, 'input[type=radio]');
});

Upvotes: 2

Related Questions