简体   繁体   中英

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 each question it would need to alert a certain output. I only have some basic knowledge of Javascript so am using the same theory of using text boxes to select an answer but this time I want to use Radio buttons.

This is the HTML code for the page with the radio buttons:

<p>
                <strong>1. This is the first question?</strong><br />
                <input type="radio" name="op1" value="anw1">Option 1<br>
                <input type="radio" name="op1" value="anw2">Option 2
            </p>

            <p>
                <strong>2. This is the second question?</strong><br />

                <input type="radio" name="op2" value="anw1">Option 1<br>
                <input type="radio" name="op2" value="anw2">Option 2

            </p>

            <input type='button' value='Get result!' onClick='Submit()' /><br />

I then have the function for now in the head tag like this:

function Submit()
  {

var op1 = document.getElementsByName('op1')
var op2 = document.getElementsByName('op2')


if(op1== "anw1" && op2== "anw1")
{
alert ("This would be if both options one were selected")
}

else if (op1== "anw2"&& op2== "anw2")
{
alert ("This would be if the the seconds ones were selected")
}

else
{

alert ("This would be if neither were true")

}

}

However, I cannot seem to get to work so I think I might be not going about this the right way though I do want it set out similar . i can get the else part to work but none of the other ones.

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

function Submit() {    
    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");
    } else if (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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM