Get the value of the selected switch

I defined a set of radio buttons in HTML in the form as follows. The name of my form is "MyForm". When "Woman" is selected, I want the variable to be "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 like var

 genderValue = $('input[name=gender]:checked', '#MyForm').val() 

But that does not work. What is the right way?

+4
source share
3 answers

you can save the values ​​( female , ... ), in the value attribute of the inputs, depending on your layout, you can try the following:

 $('input[name="radio-choice-1"]').change(function(){ var genderValue = $(this).next('label').text() }) 

<h / "> but I would suggest the following:

 <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 }) 
+4
source

Your problem is solved as follows:

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 made bunkers at http://codebins.com/bin/4ldqpaa

+1
source

It might help someone. Here is another way to get the selected switch value

 var gender = $('input[name="radio-choice-1"]:checked').val(); 

Setting the identifier on the radio buttons is optional.

Happy coding! ....

0
source

All Articles