I have two radio buttons and want to post the value of the selected one. How can I get the value with jQuery?
I can get all of them like this:
JavaScript
x
2
1
$("form :radio")
2
How do I know which one is selected?
Advertisement
Answer
To get the value of the selected radioName
item of a form with id myForm
:
JavaScript
1
2
1
$('input[name=radioName]:checked', '#myForm').val()
2
Here’s an example:
JavaScript
1
3
1
$('#myForm input').on('change', function() {
2
alert($('input[name=radioName]:checked', '#myForm').val());
3
});
JavaScript
1
9
1
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
2
<form id="myForm">
3
<fieldset>
4
<legend>Choose radioName</legend>
5
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
6
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
7
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
8
</fieldset>
9
</form>