Tuesday, May 29, 2012

How can I get which radio is selected via jQuery?


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")



But how do I know which one is selected?


Source: Tips4all

10 comments:

  1. To get the value of the selected radioName item of a form called 'myForm':

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

    ReplyDelete
  2. Use this..

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

    ReplyDelete
  3. The example above using the find() function is not correct.

    Instead, 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 elements, whereas filter() searches top-level elements in your selection.)

    var checkedValue = myRadio.filter(':checked').val();

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

    $("form:radio:checked").val();

    ReplyDelete
  5. This should work:

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


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

    ReplyDelete
  6. Another option is:

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

    ReplyDelete
  7. In a JSF generated radio button (using <h:selectOneRadio> tag), you can do this:

    radiobuttonvalue = jQuery("input[name='form_id\:radiobutton_id']:checked").val();


    where selectOneRadio ID is radiobutton_id and form ID is form_id.

    Be sure to use name instead id, as indicated, because jQuery uses this attribute (name is generated automatically by JSF resembling control ID).

    ReplyDelete
  8. Get all radios:

    var radios = jQuery("input[type='radio']");

    Filter to get the one thats checked

    radios.filter(":checked")

    ReplyDelete
  9. $("input:radio:checked").val();

    ReplyDelete
  10. Also, check if the user does not select anything.

    var radioanswer = 'none';
    if ($('input[name=myRadio]:checked').val() != null) {
    radioanswer = $('input[name=myRadio]:checked').val();
    }

    ReplyDelete