Find out whether radio button is checked with JQuery?
Asked Answered
E

18

645

I can set a radio button to checked fine, but what I want to do is setup a sort of 'listener' that activates when a certain radio button is checked.

Take, for example the following code:

$("#element").click(function()
{ 
    $('#radio_button').attr("checked", "checked");
});

it adds a checked attribute and all is well, but how would I go about adding an alert. For example, that pops up when the radio button is checked without the help of the click function?

Emblazon answered 16/2, 2010 at 11:33 Comment(2)
possible duplicate of Check of specific radio button is checkedParticularity
related Monitoring when a radio button is unchecked #5825139Irradiant
L
1198
$('#element').click(function() {
   if($('#radio_button').is(':checked')) { alert("it's checked"); }
});
Lifesaver answered 16/2, 2010 at 11:38 Comment(9)
Bingo! thanks David. So would I have to invoke an action (click etc) to show the alert? Is there a way to do this without clicking?Emblazon
well, you could run the is(':checked') check whenever. so if you want to show something on page load, depending on whether a checkbox is checked, for instance, you can just put the same if statement in page load.Lifesaver
This doesn't solve the "without the help of the click function", does it?Hilar
@Znarkus: OP appears satisfied. would you argue that you own use of ('#radio_button').click is without click?Lifesaver
I thought he was refering to his click function. If OP has tested your solution and it works for him, all is good :)Hilar
Please also add explanation as to where should others add their code. So which fields to substitute in this with what?. ThanksPlash
@David Second line should be if ($('#radio_button').is(':checked'))) { alert("it's checked"); } - you forgot the jQuery $ sign and then need to wrap it all in some more parenthesis.Geronimo
@zua: you're right! it even had a syntax error, the way it was before (unmatched brackets). fixedLifesaver
"So would I have to invoke an action (click etc) to show the alert? Is there a way to do this without clicking?" - Okay, I know this is kinda old, but this might help others. If you want to invoke it without using click event, you can use document ready event.Arevalo
C
178

If you have a group of radio buttons sharing the same name attribute and upon submit or some event you want to check if one of these radio buttons was checked, you can do this simply by the following code :

$(document).ready(function(){
  $('#submit_button').click(function() {
    if (!$("input[name='name']:checked").val()) {
       alert('Nothing is checked!');
        return false;
    }
    else {
      alert('One of the radio buttons is checked!');
    }
  });
});

Source

jQuery API Ref

Consensus answered 1/7, 2011 at 6:1 Comment(2)
This did not work for me. If I alert($("input[@name='shipping_method']:checked").val()); it still gives me the value even if the radio button is not selected.Doti
Note: If you have several forms with groups of radio buttons using the same name, you need to make sure to check only those of the form that is submitted. One option to do this is using the find method on the form: $('#myform').submit(function(event){ if (!$(this).find("input[name='name']:checked").val()) {Anthropomorphosis
G
54

As Parag's solution threw an error for me, here's my solution (combining David Hedlund's and Parag's):

if (!$("input[name='name']").is(':checked')) {
   alert('Nothing is checked!');
}
else {
   alert('One of the radio buttons is checked!');
}

This worked fine for me!

Guide answered 7/6, 2013 at 13:26 Comment(0)
H
38

You'd have to bind the click event of the checkbox, as the change event doesn't work in IE.

$('#radio_button').click(function(){
    // if ($(this).is(':checked')) alert('is checked'); 
    alert('check-checky-check was changed');
});

Now when you programmatically change the state, you have to trigger this event also:

$('#radio_button').attr("checked", "checked");
$('#radio_button').click();
Hilar answered 16/2, 2010 at 11:57 Comment(0)
E
28

//Check through class

if($("input:radio[class='className']").is(":checked")) {
     //write your code         
}

//Check through name

if($("input:radio[name='Name']").is(":checked")) {
         //write your code         
}

//Check through data

if($("input:radio[data-name='value']").is(":checked")) {
         //write your code         
}
Extractive answered 6/1, 2014 at 11:51 Comment(0)
F
13

Another way is to use prop (jQuery >= 1.6):

$("input[type=radio]").click(function () {
    if($(this).prop("checked")) { alert("checked!"); }
});
Fly answered 19/9, 2015 at 13:25 Comment(1)
Indeed .prop() is much faster, and simply easier to type.Melanymelaphyre
B
13

The solution will be simple, As you just need 'listeners' when a certain radio button is checked. Do it :-

if($('#yourRadioButtonId').is(':checked')){ 
// Do your listener's stuff here. 
}
Baptiste answered 24/5, 2017 at 9:10 Comment(0)
S
10

Working with all types of Radio Buttons and Browsers

if($('#radio_button_id')[0].checked) {
   alert("radiobutton checked")
}
else{
   alert("not checked");
}

Working Jsfiddle Here

Steepen answered 1/6, 2016 at 7:24 Comment(0)
E
8

... Thanks guys... all I needed was the 'value' of the checked radio button where each radio button in the set had a different id...

 var user_cat = $("input[name='user_cat']:checked").val();

works for me...

Ejectment answered 14/9, 2013 at 12:8 Comment(0)
S
7

If you don't want a click function use Jquery change function

$('#radio_button :checked').live('change',function(){
alert('Something is checked.');
});

This should be the answer that you are looking for. if you are using Jquery version above 1.9.1 try to use on as live function had been deprecated.

Spelt answered 2/5, 2013 at 7:49 Comment(0)
H
6

ULTIMATE SOLUTION Detecting if a radio button has been checked using onChang method JQUERY > 3.6

         $('input[type=radio][name=YourRadioName]').change(()=>{
             alert("Hello"); });

Getting the value of the clicked radio button

 var radioval=$('input[type=radio][name=YourRadioName]:checked').val();
Heuer answered 16/1, 2021 at 4:43 Comment(0)
C
4

dynamic generated Radio Button Check radio get value

$("input:radio[name=radiobuttonname:checked").val();

On change dynamic Radio button

$('input[name^="radioname"]').change(function () {if (this.value == 2) { }else{}});
Caesarea answered 18/5, 2016 at 7:47 Comment(0)
M
4

$('.radio-button-class-name').is('checked') didn't work for me, but the next code worked well:

    if(typeof $('.radio-button-class-name:checked').val() !== 'undefined'){
     // radio button is checked
    }
Manservant answered 3/7, 2017 at 14:19 Comment(1)
Since your used it with a class instead of an ID, it would have returned a nodelist, instead of an element. $('.radio-button-class-name').first().is(':checked') should have worked.Lindquist
R
4

jQuery is still popular, but if you want to have no dependencies, see below. Short & clear function to find out if radio button is checked on ES-2015:

function getValueFromRadioButton( name ){
  return [...document.getElementsByName(name)]
         .reduce( (rez, btn) => (btn.checked ? btn.value : rez), null)
}

console.log( getValueFromRadioButton('payment') );
<div>  
  <input type="radio" name="payment" value="offline">
  <input type="radio" name="payment" value="online">
  <input type="radio" name="payment" value="part" checked>
  <input type="radio" name="payment" value="free">
</div>
Ryals answered 30/4, 2019 at 9:20 Comment(1)
When I tryed to run your code snippet here in stack overflow iIt seems not working as a test , could you edit it so we can easily try it .However It seems working on my project and very clear thank you very much.Barr
C
3

try this

    if($('input[name="radiobutton"]:checked').length == 0) {
        alert("Radio buttons are not checked");
    }
Culmination answered 30/12, 2013 at 10:37 Comment(0)
G
3

This will work in all versions of jquery.

//-- Check if there's no checked radio button
if ($('#radio_button').is(':checked') === false ) {
  //-- if none, Do something here    
}

To activate some function when a certain radio button is checked.

// get it from your form or parent id
    if ($('#your_form').find('[name="radio_name"]').is(':checked') === false ) {
      $('#your_form').find('[name="radio_name"]').filter('[value=' + checked_value + ']').prop('checked', true);
    }

your html

$('document').ready(function() {
var checked_value = 'checked';
  if($("#your_form").find('[name="radio_name"]').is(":checked") === false) {
      $("#your_form")
        .find('[name="radio_name"]')
        .filter("[value=" + checked_value + "]")
        .prop("checked", true);
    }
  }
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" id="your_form">
  <input id="user" name="radio_name" type="radio" value="checked">
        <label for="user">user</label>
  <input id="admin" name="radio_name" type="radio" value="not_this_one">
    <label for="admin">Admin</label>
</form>
Galloon answered 31/7, 2020 at 9:4 Comment(0)
D
2

Try this:

alert($('#radiobutton')[0].checked)
Dot answered 1/3, 2016 at 13:3 Comment(0)
R
-4
$("#radio_1").prop("checked", true);

For versions of jQuery prior to 1.6, use:

$("#radio_1").attr('checked', 'checked');
Rybinsk answered 27/8, 2016 at 5:27 Comment(1)
This sets the value of the checked property, instead of querying it.Melanymelaphyre

© 2022 - 2024 — McMap. All rights reserved.