Javascript check if radio button was checked?

JohnA picture JohnA · Feb 16, 2012 · Viewed 77.7k times · Source

I have found scripts that do it, but they only work with one radio button name, i have 5 different radio button sets. How can i check if its selected right now i tried on form submit

if(document.getElementById('radiogroup1').value=="") {
        alert("Please select option one");
        document.getElementById('radiogroup1').focus();
        return false;
    }

does not work.

Answer

Oliver Law picture Oliver Law · Feb 16, 2012

If you have your heart set on using standard JavaScript then:

Function definition

var isSelected = function() {
    var radioObj = document.formName.radioGroupName;

    for(var i=0; i<radioObj.length; i++) {
        if( radioObj[i].checked ) {
            return true;
        }
    }

    return false;
};

Usage

if( !isSelected() ) {
    alert('Please select an option from group 1 .');
}   

I'd suggest using jQuery. It has a lot of selector options which when used together simplify the much of the code to a single line.

Alternate Solution

if( $('input[type=radio][name=radioGroupName]:selected').length == 0 ) {
    alert('Please select an option from group 1 .');
}