Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check if radio button was checked?

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.

like image 611
JohnA Avatar asked Oct 28 '25 14:10

JohnA


2 Answers

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 .');
}
like image 106
Oliver Avatar answered Oct 31 '25 12:10

Oliver


var checked = false, radios = document.getElementsById('radiogroup1');
for (var i = 0, radio; radio = radios[i]; i++) {
    if (radio.checked) {
        checked = true;
        break;
    }
}

if (!checked) {
    alert("Please select option one");
    radios.focus();
    return false;
}

return true;
like image 35
Kevin Avatar answered Oct 31 '25 11:10

Kevin