2012-02-28 87 views
-1

我有一個名爲attendance的單選按鈕,如果未選擇「是」或「否」,我如何創建錯誤。目前用戶可以提交表單,如果任何一個按鈕沒有被選中,我不想要。如何檢查單選按鈕是否使用jquery進行檢查

<script src="jquery.js"></script> 
    <script>  
    $(function(){  
      function validate(id){  
       var enabled = ($("input[name='attendance" + id + "']:checked").val() == 'Yes');   
       if(enabled){    
        //Please select option is selected    
        if($("#colour" + id)[0].selectedIndex == 0){     
        alert('Please make your colourselection');     
        return false;    
        }    
        //Please select option is selected    
        if($("#shade" + id)[0].selectedIndex == 0){     
         alert('Please select your shade');     
         return false;  

        } 
       }  
       return true;  
      }; 

      $("input[name^='attendance']").click(function() { 

       var id = this.name.replace('attendance', '');  
       $("#colour" + id + ", #sahde" + id).prop("disabled", this.value == 'No');   
       validate(id);  
      });  
      $("input:submit").click(function(){   
       var retVal = true; 
       $.each([1, 2, 3, 4], function(i, val){ 
        retVal = (validate(val) && retVal); 
       }); 
       return retVal; 
      }); 
     }); 
    $(document).ready(function(){    
            $("input[name=attendance1]:checked").triggerHandler('click'); 

     });  

}); 
    if (!($("input[name='attendance1']:checked").val())) { 
    alert('Nothing is checked!'); 
    return false; 
    }); 
    </script> 
+0

我想你可能想看看jquery驗證插件http://docs.jquery.com/Plugins/Validation它可以讓你指定一個字段,如果沒有大量的代碼 – 2012-02-28 00:52:40

回答

0
if ($("input[name='attendance1']:checked").val()) { 
     alert('Nothing is checked!'); 
     return false; 

你缺少一個(以後如果和$聲明(「輸入[名稱=‘attendance1’]:勾選」)VAL()是當有一個選中的值,這意味着真實,觸發警報。

你可能要改變如何與

if (!($("input[name='attendance1']:checked").val())) { 
     alert('Nothing is checked!'); 
     return false; 

所以現在如果還有什麼選擇工作

,警報會觸發

+0

謝謝你可以檢查我編輯後,我試過了,它仍然沒有工作。 – lukus 2012-02-28 01:01:39

+0

if語句不應該在提交函數之外,在那裏我看不到任何代碼,你可能想看看這個http://api.jquery.com/submit/,花些時間閱讀它並改變它你的代碼相應地或者你可以看看插件,像格倫斯拉文 – XepterX 2012-02-28 01:24:03

+0

建議的是我的提交功能不是$(「input:submit」)。click(function(){? – lukus 2012-02-28 01:38:44

0

我想你只需要檢查是否複選框被選中與否,所以沒有必要爲這個校驗值只是使用

if ($("input[name='attendance1'].is(":checked")) { 
    #your code 
} 

希望這有助於..........

相關問題