harsh harsh - 4 months ago 7
Javascript Question

Get the value of the selected radio button

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?

Answer

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
})