2013-03-07 57 views
0

我已收到用戶必須選擇大學校園的作業,然後單擊繼續按鈕。我不能工作的唯一的事情是,當沒有選中單選按鈕並單擊繼續按鈕時,應該顯示一條錯誤消息,指出'您尚未選擇大學校園,請重試。'單擊需要的按鈕時出現錯誤消息

我有一切工作,但這個錯誤代碼。我似乎無法得到它。出現錯誤消息,顯示「未定義」,該按鈕來自按鈕的點擊功能。有人可以幫忙嗎?

<html> 
<head> 
    <style> 
     input, label { line-height: 1.5em; } 
    </style> 
    <script src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 
    <form> 
     <div> 
      <input type="radio" name="university" value="Ah, we are not on the same site" id="Belfast"> 
      <label for="Belfast">Belfast</label> 
     </div> 
     <div> 
      <input type="radio" name="university" value="Yeah, we are on the same campus" id="Jordanstown"> 
      <label for="Jordanstown">Jordanstown</label> 
     </div> 
     <div> 
      <input type="radio" name="university" value="Ah, we are not on the same site" id="Coleraine"> 
      <label for="Coleraine">Coleraine</label> 
     </div> 
     <div> 
      <input type="radio" name="university" value="Ah, we are not on the same site" id="Magee"> 
      <label for="Magee">Magee</label> 
     </div> 
     <div id="log"></div> 
    </form> 

    <input type="button" value="Continue" id="click"> 
</body> 
</html> 

<script> 
    $(function() { 
     $("#click").click(function() { 
      alert($("input[type=radio]:checked").val()); 
     }) 
    }); 
</script> 
+0

如果沒有選擇單選按鈕,則沒有元素的值應該返回。這應該解釋警報。至於阻止提交,請查看作爲回調參數的'event'對象。 – 2013-03-07 15:41:58

回答

0

http://jsfiddle.net/VMLg9/

$("#click").click(function(){ 
    my_val = $("input[type=radio]:checked").val(); 

    if(my_val === undefined){ 
     alert("MY_VALIDATION_ERROR"); 
    } else { 
     alert($("input[type=radio]:checked").val()); 
    } 

}) 
+0

你絕對的傳奇。非常感謝 :) – AmyLouise 2013-03-07 15:54:42

0

而不是$("input[type=radio]:checked").val()嘗試檢查長度,就像這樣:

$(function() { 
    $("#click").click(function(){ 
     if ($("input[type=radio]:checked").length == 0) { 
      alert('Your message goes here'); 
     } 
    }) 
}); 

當你使用jQuery的.val()拉選定的單選按鈕的值。由於沒有選擇單選按鈕,您可以獲得undefined。如果您使用.length,jQuery將返回與您的選擇器字符串匹配的元素數量。在這種情況下,如果沒有選中,你將得到一個0.

相關問題