Get the value of the selected radio button
11,467
Solution 1
you can store the values(female
,...
), in value attribute of the inputs, based on your markup you can try the following:
$('input[name="radio-choice-1"]').change(function(){
var genderValue = $(this).next('label').text()
})
but I'd suggest this one:
<fieldset data-role="controlgroup" data-type="horizontal" id="gender" name="gender">
<legend>Gender :</legend>
<input type="radio" name="radio-choice-1" id="radio-choice-1" value="Male" checked="checked" />
<label for="radio-choice-1">Male</label>
<input type="radio" name="radio-choice-1" id="radio-choice-2" value="Female"/>
<label for="radio-choice-2">Female</label>
</fieldset>
$('input[name="radio-choice-1"]').change(function(){
var genderValue = this.value
})
Solution 2
Your issue has been solved as below:
HTML:
<form id="MyForm" name="MyForm" method="post">
<fieldset>
<legend>
Gender
</legend>
<div id="panel">
<input type="radio" name="radio-choice" id="radio-choice-1" value="choice-1" />
<label for="radio-choice-1">
Male
</label>
<input type="radio" name="radio-choice" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">
Female
</label>
</div>
<div id="result">
</div>
</fieldset>
</form>
jQuery:
$(function() {
$('input[name="radio-choice"]').change(function() {
var genderValue = $(this).next('label').text();
$("#result").html("<p> You have selected " + genderValue + ".");
})
});
I have done bins on http://codebins.com/bin/4ldqpaa
Solution 3
This might helpful to someone, Here is another way to retrieve selected radio button value
var gender = $('input[name="radio-choice-1"]:checked').val();
Setting id to radio buttons is optional here.
Happy coding!....
Author by
harsh
Updated on August 21, 2022Comments
-
harsh over 1 year
I have defined a set of radio buttons in HTML in a form as follows. The name of my form is "MyForm". When Female is selected, I want the value of a variable to be equal to "Female".
<fieldset data-role="controlgroup" data-type="horizontal" id="gender" name="gender"> <legend>Gender :</legend> <input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked" /> <label for="radio-choice-1">Male</label> <input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2"/> <label for="radio-choice-2">Female</label> </fieldset>
I tried as var
genderValue = $('input[name=gender]:checked', '#MyForm').val()
But this is not working. What is the correct way?