Categories
html javascript jquery jquery-selectors radio-button

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

2975

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?

    4202

    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">
      <fieldset>
        <legend>Choose radioName</legend>
        <label><input type="radio" name="radioName" value="1" /> 1</label> <br />
        <label><input type="radio" name="radioName" value="2" /> 2</label> <br />
        <label><input type="radio" name="radioName" value="3" /> 3</label> <br />
      </fieldset>
    </form>

    4

    • 8

      Just going to add this because it might help someone. If the name of the radio has brackets like radioName[0] (sometimes used in WordPress), you will want to use quotes around the name like input[name=’radioName[0]’]:checked

      – ZeroNine

      Dec 21, 2020 at 5:07

    • 1

      Just noting, in the onChange method example, you can also use this.value instead of $(‘input[name=radioName]:checked’, ‘#myForm’).val() 🙂

      Feb 25, 2021 at 19:39

    • For a non-jquery version, see here: jsfiddle.net/2y76vp1e

      Mar 28, 2021 at 5:54

    • @ ZeroNine, that’s also the case in Symfony framework that I use.

      – Ali

      Jun 19, 2021 at 7:41

    451

    Use this..

    $("#myform input[type="radio"]:checked").val();
    

    0

      336

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

      0