繁体   English   中英

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

[英]Selecting Multiple Radio Buttons With Alert

基本上,我想创建一个具有类似测验结构的页面,用户可以从一个问题中选择一个选项,而从另一个问题中选择另一个选项。 根据每个问题的答案,将需要警告某个输出。 我只了解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 />

我现在在head标签中具有如下功能:

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")

}

}

但是,我似乎无法上班,因此我认为我可能不会以正确的方式进行此操作,尽管我确实希望将其设置为类似的方法。 我可以让其他部分工作,但其他都没有。

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

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

演示: http//jsfiddle.net/Hy9Nw/1

getElementsByName()函数返回一个列表(实际上是一个HTMLCollection ),而不是单个元素,因此您不能像代码中那样仅比较op1== "anw1" 即使它是单个元素,也需要说op1.value == "anw1"

要访问由getElementsByName()返回的op1列表中的各个项目,可以将数组语法与op1[0] ,并通过使用op1[0].checked (返回truefalse来测试是否对其进行检查。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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