javascript tutorial - [Solved-5 Solutions] Radio button is selected via jQuery - javascript - java script - javascript array
Problem:
We have two radio buttons and want to post the value of the selected one. How to get the value with jQuery?
Solution 1:
To get the value of the selected radioName
item of a form with id myForm
:
$('input[name=radioName]:checked', '#myForm').val()
click below button to copy the code. By JavaScript tutorial team
Here's an example:
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="radio" name="radioName" value="1" /> 1 <br />
<input type="radio" name="radioName" value="2" /> 2 <br />
<input type="radio" name="radioName" value="3" /> 3 <br />
</form>
click below button to copy the code. By JavaScript tutorial team
Solution 2:
Use this..
$("#myform input[type='radio']:checked").val();
click below button to copy the code. By JavaScript tutorial team
Solution 3:
If we already have a reference to a radio button group, for example:
var myRadio = $('input[name=myRadio]');
click below button to copy the code. By JavaScript tutorial team
Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)
var checkedValue = myRadio.filter(':checked').val();
click below button to copy the code. By JavaScript tutorial team
Note: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful in the situation where we already had a reference to a container element, but not to the radio buttons, e.g.:
var form = $('#mainForm');
...
var checkedValue = form.find('input[name=myRadio]:checked').val();
click below button to copy the code. By JavaScript tutorial team
Solution 4:
This should work:
$("input[name='radioName']:checked").val()
click below button to copy the code. By JavaScript tutorial team
Solution 5:
We can use the :checked selector along with the radio selector.
$("form:radio:checked").val();