2013-02-19 127 views
4

我想獲取一些複選框,並確保至少使用jQuery驗證檢查這些複選框中的一個。到目前爲止我還沒有運氣。我錯過了什麼?我知道我的驗證是在那裏,因爲它適用於其他領域,只是不適用於我的複選框。我把代碼放在jfiddle上,也許這會有所幫助。使用jQuery驗證驗證多個複選框

編輯:我添加了括號爲我的輸入名稱=列表參數(列表[])。同樣在我的規則中,我將列表中的名稱參數更改爲'list []'。我的舊代碼在下面。謝謝Sparky!

OLD: <input type='checkbox' name='list' id='fullProduct'></input> 

FIXED: <input type='checkbox' name='list[]' id='fullProduct'></input> 

這是我的代碼。

$("#tradeForm").validate({ 
     rules: { 
      startDate: { 
       required: true, 
       date: true 
      }, 
      endDate: { 
       required: true, 
       date: true 
      }, 
      showName: { 
       required: true, 
       minlength: 5 
      }, 
      location: { 
       required: true 
      }, 
      list: { 
       required: true 
      } 
     }, 
     messages: { 
      startDate: "*", 
      endDate: "*" 
    } 
}); 

       <table> 
       <tr> 
        <th>Name of Show</th> 
        <td> <input type='text' name='showName'></input></td> 
       </tr> 
       <tr> 
        <th>Location</th> 
        <td><input type='text' name='location'></input></td> 
       </tr> 
       <tr> 
        <th><span style='padding-right: 50px;'>Select Literature</span></th> 
        <td><input type='checkbox' name='list' id='fullProduct'></input><span style='font-size: 12px;'>Guide One</span></td> 
        <td><input type='checkbox' name='list' id='oilProduct'></input><span style='font-size: 12px;'>Guide Two</span></td> 
       </tr>        
       <tr>         
        <td></td>      
        <td><input type='checkbox' name='list' id='diamondProduct'></input><span style='font-size: 12px;'>Guide Three</span></td> 
        <td><input type='checkbox' name='list' id='motorProduct'></input><span style='font-size: 12px;'>Guide Four</span></td> 
       </tr>        
      </table> 
+0

在OP的HTML代碼是不一樣在你的jsfiddle,這也是你的問題的原因的代碼。 'name =「list []」'與'name =「list」'不一樣「。 – Sparky 2013-02-19 20:45:10

回答

15

您的複選框組中的namelist[]而不是list,因此您必須聲明規則。 Since it contains brackets, [], you must enclose it in quotes

rules: { 
    'list[]': { 
     required: true 
    } 
}, 

你的jsfiddle:http://jsfiddle.net/ZDz59/1/

+1

這是正確的答案。謝謝Sparky! – wowzuzz 2013-02-19 20:46:44

+0

如果您的表單由使用非法定JavaScript標識符的名稱組成的字段組成,則必須在使用規則選項時引用這些名稱: 這是您所指的內容嗎? – wowzuzz 2013-02-19 20:49:28

+0

@wowzuzz,是的,我指的是:http://docs.jquery.com/Plugins/Validation/Reference#Fields_with_complex_names_.28brackets.2C_dots.29 – Sparky 2013-02-19 20:53:04

1

如果你只打算在任何時候都檢查複選框之一,使用輸入類型=「無線電」代替。

如果不是,請嘗試將複選框的名稱屬性更改爲列表[]。由於可以有多個檢查值,它必須包含括號來表示它是一個數組。否則,該值將被覆蓋。

+0

我將名稱更改爲列表[],並且在我的結尾沒有運氣。它只是提交給我的表單操作。它正在驗證我的其他領域。 – wowzuzz 2013-02-19 20:17:13

+0

嘗試在列表規則中添加'minlength:1'。 – kjetilh 2013-02-19 20:23:09

+0

你可以添加一個點擊函數來取消每個方框的選擇,但是你只需點擊一個方框 – 2013-02-19 20:24:19