簡體   English   中英

在同一HTML頁面中使用Javascript獲得單選按鈕的價值

[英]Getting value of radio button with Javascript in same HTML page

我是javascript編碼的新手。

我有點自己創建調查頁面。 我會以“ True or False”(真還是假)的形式問問題,並將True表示為1點,將false表示為0點。 會有多個問題。

我試圖通過getElementsByName做到這一點,但沒有成功。 我的代碼就是這樣。 有人可以幫我嗎?

<form>
<input type="radio" name="question1" value="1" id="q1"> true
<input type="radio" name="question1" value="0" id="q1"> false
</form>
<button onclick="myFunction()">try</button>

<script>
function myFunction()
{
var x=document.getElementsByName("question1").value;
window.alert("your score is " +x);
}
</script>

按名稱分組的單選按鈕的行為與select元素不同,即,分組沒有單個值。 同樣, getElementsByName()返回HTMLCollection ,它是一個類似於數組的對象(請參見Felix Kling的評論)。

我建議您做這樣的事情(在給form提供id后):

function myFunction () {
    var form = document.getElementById('form'), // a reference to the form element
        question = form['question1'], // creates a HTMLCollection from elements having attribute name="question1"
        n; // loop index
    for (n = 0; n < question.length; n++) { // iterates through items in HTMLCollection
        if (question[n].checked) { // checks the current item's 'checked' property
            alert("your score is " + question[n].value); // found the checked-one
            break; // "checked" found, no need to search more
        }
    }
}

jsFiddle上的現場演示

question定義中的括號符號用於將來使用。 萬一您有更多的單選按鈕組(可以使用同一功能處理),可以將組的名稱傳遞給函數,然后在方括號中使用該參數而不是文字值( 'question1' )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM