Advertisement
Advertisement


How can I know which radio button is selected via jQuery?


Question

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:

$("form :radio")

How do I know which one is selected?

2020/01/10
1
2748
1/10/2020 3:06:37 PM

Accepted Answer

To get the value of the selected radioName item of a form with id myForm:

$('input[name=radioName]:checked', '#myForm').val()

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>

2018/05/04
3973
5/4/2018 8:44:30 AM

Use this..

$("#myform input[type='radio']:checked").val();
2010/01/07

If you already have a reference to a radio button group, for example:

var myRadio = $("input[name=myRadio]");

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();

Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you 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();
2018/06/07

This should work:

$("input[name='radioName']:checked").val()

Note the "" usaged around the input:checked and not '' like the Peter J's solution

2011/03/30

You can use the :checked selector along with the radio selector.

 $("form:radio:checked").val();
2012/04/24

If you want just the boolean value, i.e. if it's checked or not try this:

$("#Myradio").is(":checked")
2013/08/30

Source: https://stackoverflow.com/questions/596351
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]