views:

461

answers:

2

Hi Guys,

I can set a radio button to checked fine, but what I want to do is setup a sort of 'listener' that activates when a certain radio button is checked.

Take, for example the following code:

$("#element").click(function()
{ 
    $('#radio_button').attr("checked", "checked");
});

it adds a checked attribute and all is well, but how would I go about adding an alert. For example, that pops up when the radio button is checked without the help of the click function?

Cheers, Keith

+2  A: 
$('#element').click(function() {
   if('#radio_button').is(':checked')) { alert("it's checked"); }
});
David Hedlund
Bingo! thanks David. So would I have to invoke an action (click etc) to show the alert? Is there a way to do this without clicking?
Keith Donegan
well, you could run the `is(':checked')` check whenever. so if you want to show something on page load, depending on whether a checkbox is checked, for instance, you can just put the same if statement in page load.
David Hedlund
This doesn't solve the "without the help of the click function", does it?
Znarkus
@Znarkus: OP appears satisfied. would you argue that you own use of `('#radio_button').click` is without `click`?
David Hedlund
I thought he was refering to his click function. If OP has tested your solution and it works for him, all is good :)
Znarkus
+1  A: 

You'd have to bind the click event of the checkbox, as the change event doesn't work in IE.

$('#radio_button').click(function(){
    // if ($(this).is(':checked')) alert('is checked'); 
    alert('check-checky-check was changed');
});

Now when you programmatically change the state, you have to trigger this event also:

$('#radio_button').attr("checked", "checked");
$('#radio_button').click();
Znarkus