Selecting Multiple Radio Buttons With Alert

痞子三分冷 提交于 2021-01-29 22:01:00

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/17132373/selecting-multiple-radio-buttons-with-alert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!