2014-02-07 147 views
0

我試圖驗證一組單選按鈕,它們在提交時輸出一條消息,通知用戶他們必須在繼續之前做出選擇。下面的代碼永遠不會識別按鈕被選中,並始終輸出警報消息。我將如何調整此代碼以使其工作?如何驗證單選按鈕?

單選按鈕:

<input type="radio" name="examtype" value="GCSE"onclick="return confirmation();"/>GCSE 

<input type="radio" name="examtype" value="AS" onclick="return confirmation();"/> AS 

<input type="radio" name="examtype" value="A2" onclick="return confirmation();"/> A2 </td> </tr> 

功能進行確認的onclick:

function confirmation() { 

    for (var i=0; i < document.ExamEntry.examtype.length; i++) 
     { 
     if (document.ExamEntry.examtype[i].checked) 
      { 
      var answer = confirm(document.ExamEntry.examtype[i].value) 

     if (answer){ 
      document.ExamEntry.examtype[i].checked = true; 

     } 
     else{ 
      document.ExamEntry.examtype[i].checked = false; 


     } 
      } 
    } 

    } 

代碼當前正用於拒絕未選擇的單選按鈕:

if (document.ExamEntry.examtype.checked){ 
     alert('checked') //for testing if statement runs when appropriate// 
} 

else { 
msg+="You must enter the exam type \n"; 
result = false; 
} 
+0

添加類的單選按鈕,請參閱鏈接http://stackoverflow.com/questions/3414105/how-to-validate-radio-buttons-in-javascript?rq=1 –

+1

你爲什麼需要confirm()。沒有提及它在代碼中的表現。 – Jobin

+0

我在網上發現了特定的代碼,但是當我改變它的時候它停止了工作,所以我就這樣離開了它? @Beauflitz – user3276816

回答

0

下面是關於如何驗證選項框的示例代碼:http://jsfiddle.net/jyUAM/3/

<script type="text/javascript"> 
function validateRadioboxesByName(form, name) 
{ 
    var el = form[name]; 
    for (i = 0; i < el.length; ++i) { 
     if (el[i].checked) 
      return true; 
    } 

    return false; 
} 

function checkRegistration() { 
    var isValid = validateRadioboxesByName(document.forms.test, "examtype"); 

    if (!isValid) 
     alert("Please check one of the radiobox."); 

    return isValid; 
} 
</script> 

<form name="test" onsubmit="return checkRegistration()"> 
    <input type="radio" name="examtype" value="GCSE"/>GCSE 

    <input type="radio" name="examtype" value="AS"/> AS 

    <input type="radio" name="examtype" value="A2"/> A2 

    <button type="submit">Send</button> 
</form> 

這樣你就不需要記住點擊radiobox的狀態,但只要問一下瀏覽器的時候,你需要的數據,也就是說,在提交前數據。

本教程可以給你如何以可視化的信息給用戶,而不是使用一個醜陋的alert調用更多的想法:http://www.the-art-of-web.com/html/html5-checkbox-required/

這最後一個環節的例子是複選框不應該嚇唬你,你可以很容易地應用於無線電輸入盒等。

+0

不幸的是,我不得不使用警報呼叫,其設置在條件:/另外它不是一個複選框其單選按鈕,所以我不知道這是否會工作,謝謝你,雖然我一定會嘗試它 – user3276816

+0

@ user3276816,對不起 - 一直在談論無線電臺。相應地更新了答案。希望現在有所幫助:) – SimonSimCity

0

嘗試在兩個函數之外將變量設置爲false,然後如果確認函數運行,則將該變量賦值爲true。

然後在您檢查用戶是否單擊單選按鈕的下一個函數中,使用僅在變量設置爲false(可能包含警報消息)時才運行的if語句。

希望這有助於:)

+0

你可以提供一些代碼以獲得更好的答案! – Jensd