2012-05-17 58 views
0

我的表單中只有一個複選框被選中時才顯示。因此,只有在複選框被選中的情況下,我們對tho字段的驗證纔會生效。我的代碼不起作用。驗證取決於複選框?

這是我走到這一步,並發現了這個信息:

http://docs.jquery.com/Plugins/Validation

// Validation 

function validateForm() { 
    $('#frmMain').validate({ 
     rules: { 

      SuretyFullName: { required: '#chkSurety:checked' } //if required: true it works all the time. 
     }, 
     messages: { 
      SuretyFullName: { required: 'Required' } 
     }, 

     submitHandler: function (form) { 
      $('#btnSubmit').click(); 

     } 
    }); 
} 

代碼編輯:以下建議:形式變得無響應:

$(document).ready(function(){ 
    $("#btnSubmit").click(function(){ 
if($('#chkSurety').is(":checked")) 
{ 
function validatesurety(){ 
$('#frmMain').validate({ 
rules: {  
      SuretyFullName: { required: true } 
      }, 
     messages: { 
      SuretyFullName: { required: 'Required' } 
     } 
    }); 
} 

回答

1
function validateForm() { 
    $('#frmMain').validate({ 
     rules: { 

      SuretyFullName: { required: function (element) { if ($('#chkSuretyShip').is(':checked')) { return true } else { return false} } },   
     }, 
     messages: { 
      SuretyFullName: { required: 'Required' } 
     }, 

     submitHandler: function (form) { 
      $('#btnSubmit').click(); 

     } 
    }); 
}  
2

你可以檢查它是否發現並運行你的功能

$(document).ready(function(){ 
//the submit click 
     $("#submit").click(function(){ 
    if($('#checkboxid').is(":checked"))// check if the checkbox checked if yes 
    { 
    //then call you function 
    function validateForm() ; 
    } 
     }); 
    }); 
+0

但我的驗證是整個形式?那麼只有當我的複選框被選中時纔會進行任何驗證。 – Pomster

+0

你基本上運行驗證功能,你激活它,如果複選框被選中更多的解釋上面 –

+0

我試過這個,但做了一個新的函數Validatesurety(),但這是行不通的。 $(文檔)應該保留爲文檔還是需要更改爲某個文檔? – Pomster

2

將這個你validateForm函數中:

// set the default rules 
var rules = { 
    SuretyFullName: { required: false }, 
    SuretyIDNumber: { required: true}, 
    SuretyPhysicalAddress: { required: true }, 
    SuretyHomeTel: { required: true}, 
    SuretyPlace: { required: true}, 
    SuretyDay: { required: true }, 
    SuretyMonth: { required: true } 
}; 

// override the full name rule, based on the checkbox 
rules.SuretyFullName.required = $('#chkSurety').is(':checked'); 

$('#fmrMain').validate({ 
     rules: rules, 
     ... 
});