Skip to content Skip to sidebar Skip to footer

Selecting Multiple Radio Buttons With Alert

Basically, I want create a page that has a quiz like structure and the user can select one option from one question and another from another question. Depending on the answers to e

Solution 1:

The following version will do what your code was trying to do:

functionSubmit() {    
    var op1= document.getElementsByName('op1');
    var op2= document.getElementsByName('op2');

    if (op1[0].checked && op2[0].checked) {
        alert("This would be if both options one were selected");
    } elseif (op1[1].checked && op2[1].checked) {
        alert("This would be if the the seconds ones were selected");
    } else {    
        alert("This would be if neither were true");
    }    
}

Demo: http://jsfiddle.net/Hy9Nw/1

The getElementsByName() function returns a list (actually an HTMLCollection), not a single element, so you can't just compare op1== "anw1" like in your code. Even if it was a single element you'd need to say op1.value == "anw1".

To access the individual items in the op1 list returned by getElementsByName() you can use array syntax with op1[0], and test whether it is checked by using op1[0].checked - which returns true or false.

Post a Comment for "Selecting Multiple Radio Buttons With Alert"