ChatGPT解决这个技术问题 Extra ChatGPT

How can I know which radio button 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")

How do I know which one is selected?


A
Andy

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

Choose radioName



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
Just noting, in the onChange method example, you can also use this.value instead of $('input[name=radioName]:checked', '#myForm').val() :)
For a non-jquery version, see here: jsfiddle.net/2y76vp1e
@ ZeroNine, that's also the case in Symfony framework that I use.
J
Joberror

Use this..

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

D
Daniel Marín

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

C
Cam Tullos

This should work:

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

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


Why does this returns me "on" instead of the value of the selected radio button?
t
tvanfosson

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

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

This looks nice, however, the jQuery documentation recommends using [type=radio] rather than :radio for better performance. It is a tradeoff between readability and performance. I normally take readability over performance on such trivial matters, but in this case I think [type=radio] is actually clearer. So in this case it would look like $("form input[type=radio]:checked").val(). Still a valid answer though.
J
Juan

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

$("#Myradio").is(":checked")

A
Alex V

Get all radios:

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

Filter to get the one thats checked

radios.filter(":checked")

R
RedDragon

Another option is:

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

The ":radio" part isn't necessary here.
C
Code Maverick
$("input:radio:checked").val();

O
Olivier Pons

In my case I have two radio buttons in one form and I wanted to know the status of each button. This below worked for me:

// get radio buttons value console.log( "radio1: " + $('input[id=radio1]:checked', '#toggle-form').val() ); console.log( "radio2: " + $('input[id=radio2]:checked', '#toggle-form').val() );


What do you mean the status of each button? radio buttons with the same name allows only one to be checked, therefor, if you get the checked one, the rest are unchecked.
D
Darin Peterson

Here's how I would write the form and handle the getting of the checked radio.

Using a form called myForm:

<form id='myForm'>
    <input type='radio' name='radio1' class='radio1' value='val1' />
    <input type='radio' name='radio1' class='radio1' value='val2' />
    ...
</form>

Get the value from the form:

$('#myForm .radio1:checked').val();

If you're not posting the form, I would simplify it further by using:

<input type='radio' class='radio1' value='val1' />
<input type='radio' class='radio1' value='val2' />

Then getting the checked value becomes:

    $('.radio1:checked').val();

Having a class name on the input allows me to easily style the inputs...


F
Francisco Alvarado

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


e
epascarello

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

s
swiftBoy

If you have Multiple radio buttons in single form then

var myRadio1 = $('input[name=radioButtonName1]');
var value1 = myRadio1.filter(':checked').val();

var myRadio2 = $('input[name=radioButtonName2]');
var value2 = myRadio2.filter(':checked').val();

This is working for me.


J
JGrinon

I wrote a jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.

(function ($) {

    function changeRadioButton(element, value) {
        var name = $(element).attr("name");
        $("[type=radio][name=" + name + "]:checked").removeAttr("checked");
        $("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
        $("[type=radio][name=" + name + "]:checked").change();
    }

    function getRadioButton(element) {
        var name = $(element).attr("name");
        return $("[type=radio][name=" + name + "]:checked").attr("value");
    }

    var originalVal = $.fn.val;
    $.fn.val = function(value) {

        //is it a radio button? treat it differently.
        if($(this).is("[type=radio]")) {

            if (typeof value != 'undefined') {

                //setter
                changeRadioButton(this, value);
                return $(this);

            } else {

                //getter
                return getRadioButton(this);

            }

        } else {

            //it wasn't a radio button - let's call the default val function.
            if (typeof value != 'undefined') {
                return originalVal.call(this, value);
            } else {
                return originalVal.call(this);
            }

        }
    };
})(jQuery);

Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.

You can visit this jsFiddle to try it in action, and see how it works.

Fiddle


T
Tisho
 $(".Stat").click(function () {
     var rdbVal1 = $("input[name$=S]:checked").val();
 }

M
Manoj

This works fine

$('input[type="radio"][class="className"]:checked').val()

Working Demo

The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.

API for :checked Selector


S
Samsul Islam

try this one. it worked for me

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

R
Rodrigo Dias

To get the value of the selected radio that uses a class:

$('.class:checked').val()

L
Lafif Astahdziq

I use this simple script

$('input[name="myRadio"]').on('change', function() {
  var radioValue = $('input[name="myRadio"]:checked').val();        
  alert(radioValue); 
});

Use the click event rather than the change event if you want it to work in all browsers
a
atiquratik

Use this:

value = $('input[name=button-name]:checked').val();

M
Mehdi Bouzidi

DEMO : https://jsfiddle.net/ipsjolly/xygr065w/

$(function(){ $("#submit").click(function(){ alert($('input:radio:checked').val()); }); });

Sales Promotion 1 2 3 4 5


R
Randy Greencorn

If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:

$( "input:checked" ).val()

M
Milap

I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata

It'll give you a js object of the answers, so a form like:

<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>

will give you:

$("form").formalizeData()
{
  "favorite-color" : "blue"
}

I
Iyyappan Amirthalingam

JQuery to get all the radio buttons in the form and the checked value.

$.each($("input[type='radio']").filter(":checked"), function () {
  console.log("Name:" + this.name);
  console.log("Value:" + $(this).val());
});

M
Milap

To retrieve all radio buttons values in JavaScript array use following jQuery code :

var values = jQuery('input:checkbox:checked.group1').map(function () {
    return this.value;
}).get();

Radio buttons are not the same as checkboxes. This example uses checkboxes.
G
Gautam Rai

try it-

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

console.log(radioVal);

M
Mehdi Bouzidi

Another way to get it:

$("#myForm input[type=radio]").on("change",function(){ if(this.checked) { alert(this.value); } });

1
2


J
JoshYates1980
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
    var radValue= "";
    $(this).find('input[type=radio]:checked').each(function () {
        radValue= $(this).val();
    });
  })
});

K
Kamil Kiełczewski

Try

myForm.myOption.value

function check() { console.log( myForm.myOption.value ); }

1
2
3