crmpicco
crmpicco

Reputation: 17181

capture the value of the current (not previous) selected radio button with jQuery

I want to be able to get the value that I just selected when capturing the click of a radio button. The small snippet of code below returns the previous value, however if I click 'Male' then I want to capture it and then do something else with the gender var.

$(document).ready(function() {

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

});

<input type="radio" name="gender" value="male" />Male 
<input type="radio" name="gender" value="female" />Female

This may appear like a minor question, and likely is, but I may be missing the wood from the trees because it is late in the day.

Upvotes: 0

Views: 507

Answers (2)

VitVad
VitVad

Reputation: 336

try change event, this is better solution then click

http://jsbin.com/arohuk/1/edit

Upvotes: 0

Adil
Adil

Reputation: 148140

Use $(this).val(), It will give you the current radio button being clicked. Your code is also working fine but you are using need less selector. Check demo of your code here

Live Demo

$(document).ready(function() {

     $('input[name=gender]').click(function() {
          var gender = $(this).val(); 
     });

});

Upvotes: 2

Related Questions