Javascript 选择带有警报的多个单选按钮

Javascript 选择带有警报的多个单选按钮,javascript,html,radio-button,alert,Javascript,Html,Radio Button,Alert,基本上,我想创建一个页面,它有一个类似测验的结构,用户可以从一个问题中选择一个选项,从另一个问题中选择另一个选项。根据每个问题的答案,它需要提醒特定的输出。我只有一些Javascript的基本知识,所以我使用相同的理论使用文本框来选择答案,但这次我想使用单选按钮 这是带有单选按钮的页面的HTML代码: <p> <strong>1. This is the first question?</strong><br />

基本上,我想创建一个页面,它有一个类似测验的结构,用户可以从一个问题中选择一个选项,从另一个问题中选择另一个选项。根据每个问题的答案,它需要提醒特定的输出。我只有一些Javascript的基本知识,所以我使用相同的理论使用文本框来选择答案,但这次我想使用单选按钮

这是带有单选按钮的页面的HTML代码:

<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 />

然而,我似乎无法开始工作,所以我认为我可能没有采取正确的方式,尽管我确实希望它有类似的规定。我可以让else部分工作,但其他部分都不能工作。

以下版本将执行代码试图执行的操作:

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");
    }    
}
演示:

返回的是一个列表(实际上是一个),而不是单个元素,因此您不能像在代码中那样只比较
op1==“anw1”
。即使它是单个元素,您也需要说
op1.value==“anw1”


要访问由
getElementsByName()
返回的
op1
列表中的单个项目,您可以将数组语法与
op1[0]
一起使用,并测试是否使用
op1[0]进行检查.checked
-返回
true
false

以下版本将执行代码试图执行的操作:

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");
    }    
}
演示:

返回的是一个列表(实际上是一个),而不是单个元素,因此您不能像在代码中那样只比较
op1==“anw1”
。即使它是单个元素,您也需要说
op1.value==“anw1”


要访问由
getElementsByName()
返回的
op1
列表中的单个项目,您可以将数组语法与
op1[0]
一起使用,并测试是否使用
op1[0]进行检查.checked
-返回
true
false

我可以用同样的方法来检查它们是否都没有被检查吗?当然可以<代码>如果(!(op1[0]。选中的| | op1[1]。选中的| | op2[0]。选中的| | op2[1]。选中的)){alert(“None checked”)}我可以用同样的方法检查它们是否都没有被选中吗?当然可以<代码>如果(!(op1[0]。选中| | op1[1]。选中| | op2[0]。选中| | op2[1]。选中)){警报(“未选中”)}