2011-01-06 55 views
1

我有一個基本的複選框,點擊功能,只允許用戶點擊每個字段集內只有一個複選框(有四個字段集每個包含numberous複選框:JQuery驗證和複選框點擊功能

$(document).ready(function(){ 

$('input[type=checkbox]').click(function(){ 

    // get the fieldset class 
    var fieldset = $(this).parents('fieldset').attr('class'); 

    // set the number of checked 
    var numChecked = $('.'+fieldset+' input:checked').size(); 

    // if more than 1 
    if(numChecked > 1){ 
     alert('Please select only one option per breakout session.') 

$(本) .attr(「檢查」,FALSE);}

}); 

然後我有將確認發佈的形式之前,至少一個複選框被選中窗體上的一個提交函數:

$('form[name=mainForm]').submit(function(){ 

    var error = ''; 

    // loop through each fieldset 
    $('fieldset',this).each(function(){ 

     // set the number of checked for this fieldset 
     var numChecked = $('input:checked',this).size(); 

     // if none are checked 
     if(!numChecked){ 
      // set the error var 
      error = 'At least one of your time sessions has no checkbox selected!'; 
      // add class to show user 
      $(this).addClass('errorSessions'); 
     } 
     else{ 
      $(this).removeClass('errorSessions'); 
     } 

    }); 

    // if any errors, show them and don't allow the form to be submitted 
    if(error.length){ 
     alert(error); 
     return false; 
    } 

    $("#mainForm").validate(); 

表格完美驗證,第一次完美無瑕。問題是,如果您提交表單,則會發生驗證,並提示錯誤「您的至少一個時間會話沒有選中複選框!」 - 在這一點上,如果您繼續在給定字段集中選擇最初未檢查的多個複選框,它將忽略複選框單擊功能,並允許您在字段集中選擇多個複選框。

有人可以幫忙嗎?

回答

1

好吧,我想通了。該錯誤與腳本將類「errorsessions」添加到更改字段集的唯一類名的字段集有關。通過爲每個字段集添加一個唯一的id,然後將腳本更改爲引用.attr('id');而不是.attr('class');問題解決,點擊提醒功能在課程添加完成後恢復。

0

您是否考慮使用單選按鈕,因爲它們是單選的?這樣您就不必檢查多重選擇,因爲在給定組中不能選擇多個單選按鈕。

+0

我曾經考慮過,但是表單有點複雜......我也有一個更改函數,它對於多個字段集中具有相同名稱的每個複選框發生,以在相同的字段集上禁用重複的複選框時在給定的字段集中選擇一個。我記得用單選按鈕來試這個,但它不起作用,但我可以再試一次。但是,我想知道爲什麼在發送ajax驗證請求時,第一種情況下函數被禁用了?還是它有改變班的東西? – jweisberg 2011-01-06 22:12:52