Tuesday, June 26, 2012

Check if radio button is checked or selected using jQuery

Yesterday I need to find out if radio button is checked/selected or not using jQuery. I was knowing one way to find out but there are couple of other ways as well to find out if radio button is checked using jQuery. In this post, you will find all different possible ways.

1. First Way:

Below single line of code will provide the status of radio button using jQuery. It checks whether the checked property is checked or not using jQuery and will return true or false. Below code will work with jQuery 1.7.2 version.
var isChecked = $('#rdSelect').prop('checked');
Check Yourself.

If you are using older version of jQuery (before 1.7.2) then you can use below code.
var isChecked = $('#rdSelect').attr('checked')?true:false;
I have noticed that on many website it is written that 'checked' attribute will return true or false if used with 'attr' method, but this is not correct. If the checked box is checked then it return status as "checked", otherwise "undefined".

Check Yourself.
So if you want to have true or false, then you need to use conditional expression as I have done in the code.

2. Second Way
var isChecked = $('#rdSelect:checked').val()?true:false;
$('#rdSelect:checked').val() method returns "on" when radio button is checked and "undefined", when radio button is unchecked.

3. Third Way
var isChecked = $('#rdSelect').is(':checked');
The above method uses "is" selector and it returns true and false based on radio button status.

Check Yourself.

4. Fourth Way

The below code is to find out all the radio button checked through out the page.
$("input[type=radio][checked]").each( 
    function() { 
       // Your code goes here...
    } 
);
Feel free to contact me for any help related to jQuery, I will gladly help you.