簡體   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