views:

112

answers:

3

There are many input radio elements on a web page and each radio element has several options. I want a function to be fired whenever one option of a radio element is checked. How to write the code using Jquery? One input element looks as follows:

<div class="below">
<input type="radio" value="information" name="option0"/>
information
<input type="radio" value="communication" name="option0"/>
communication
<input type="radio" value="goods" name="option0"/>
goods
<input type="radio" value="attention" name="option0"/>
attention
</div>

I wrote the code as follows:

$(":radio").checked(function() {
    alert(this.value);

});

But it doesn't work. How to do it?

+1  A: 

Try:

$(':radio').click(function(evt){
    if ($(this).attr('checked'))
    {
        alert($(this).val());
    }
});
Darrell Brogdon
gta freking love jquery!
The_Butcher
It doesn't work.unknown pseudo-class or pseudo-element 'radio'
Steven
You're right. It should be 'input[type="radio"]'.
Darrell Brogdon
+3  A: 

checked is not an event, you should use click or change.

Also I want to notice that is recommended to use input:radio instead of only :radio, because that pseudo-selector will be evaluated as *:radio and it can be quite slow:

$('input:radio').click(function () {
  if (this.checked) { // or $(this).attr('checked')
    alert(this.value); // or alert($(this).val());
  }
});
CMS
It doesn't work.unknown pseudo-class or pseudo-element 'radio'
Steven
Which version of jQuery are you using? AFAIK, the `:radio` selector has been out there since the very early versions. You can check a sample of the code I posted, with your markup here: http://jsbin.com/utipo
CMS
Yes it works in your sandbox. But it doesn't work on my computer. Don't know why
Steven
I added <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>, but still it doesn't work.
Steven
I am using Firefox. On the error console, it says "unknown pseudo-class or pseudo-element 'radio' "
Steven
That's normal and shouldn't stop it from working. jQuery tries to speed up some document queries by using the new Selectors-API to get the browser to do the matching. However `:radio` isn't a standard CSS selector (not even CSS3), it's one of the invented ones Sizzle implements, so Firefox gives you a warning. jQuery catches the resulting exception and uses the old, slower Sizzle code in that case.
bobince
So how to solve this problem?
Steven
The input radio code is dynamically created using Jquery.
Steven
A: 

I think something like this should do it.

$("input:checked").each(function(){
 alert($(this).val());
}
RageZ
It doesn't work.
Steven