views:

6908

answers:

5

I am having 4 radiobuttons in my web page like below:

<label for="theme-grey"><input type="radio" id="theme-grey" name="theme" value="grey" />Grey</label>
<label for="theme-grey"><input type="radio" id="theme-grey" name="theme" value="pink" />Pink</label>
<label for="theme-grey"><input type="radio" id="theme-grey" name="theme" value="green" />Green</label>

Now in jQuery I want to get the value of selected radiobutton on click of any radiobutton out of above three. In jQuery we have id (#) and class (.) selectors but what if I want to put event on radiobutotn using thier names? as below?

$("<radiobutton name attribute>").click(function(){});

Please tell me how to solve this problem.

Thanks

+2  A: 

Something like this maybe?

$("input:radio[name=theme]").click(function() { 
 ...
});

When you click on any radio button, I believe it will end up selected, so this is going to be called for the selected radio button.

tschaible
The @ is invalid as of jQuery 1.3 (deprecated prior to that, even). http://blog.jquery.com/2009/01/05/help-test-jquery-13-beta-2/"Old, XPath, style attribute selectors: [@attr=value]. These have been deprecated for quite some time - and we’re finally removing them. To fix it just remove the @!"
simplemotives
Thanks for pointing out ... editing my post.
tschaible
+9  A: 

This should do it, all of this is in the documentation, which has a very similar example to this:

$("input:radio[name=theme]").click(function() {
    var value = $(this).val();
});

I should also note you have multiple identical IDs in that snippet. This is invalid HTML. Use classes to group set of elements, not IDs, as they should be unique.

Paolo Bergantino
working for me....
Prashant
+4  A: 

To determine which radio button is checked, try this:

$('input:radio[name=theme]').click(function() {
  var val = $('input:radio[name=theme]:checked').val();
});

The event will be caught for all of the radio buttons in the group and the value of the selected button will be placed in val.

Update: After posting I decided that Paolo's answer above is better, since it uses one less DOM traversal. I am letting this answer stand since it shows how to get the selected element in a way that is cross-browser compatible.

jeff.mitchel
Thank you very very much!
griegs
A: 

$('input:radio[name=theme]').bind( 'click', function(){ $(this).val(); });

+4  A: 

Just want to point out that Jeff's answer might suit others because it can be used to get the value from anywhere, not just within a click handler for the radio button.

$('input:radio[name=theme]:checked').val();
Clayton Rabenda
This is correct answer.
Pawka