2016-12-18 53 views
0

我需要一些輸入,只有在另一個輸入(無線電)中檢查某些選項時才需要。簡而言之,如果選擇第1類文件,我需要第1類字段號碼爲強制性的。通過下面的這個jsfiddle可以更容易地看到: https://jsfiddle.net/kbhatd51/2/從單選按鈕不工作Jquery驗證插件依賴項

你能幫我嗎?在此先感謝

<form id="registerform" method="post"> 
    <div class="form-group"> 
    <label >Type of Document</label><br> 
    <input type="radio" class="radioForm" id="fis" name="tipop" value="0" > <label for="fis"> Type 1</label><br> 
    <input type="radio" class="radioForm" id="jur" name="tipop" value="1" > <label for="jur"> Type 2</label><br> 
    </div> 
    <label for="tipop"> Number</label> 
    <div class="form-group"> 
    <fieldset id="cpf1"> 

     <label for=cpf1>Type 1 No.:</label> 
     <input type="number" class="form-control" placeholder="000.000.000-00" name="cpf" id="cpf" > 
    </fieldset> 

    <fieldset id="cnpj1"> 
     <label for=cnpj1> Type 2 No.: 
     <input type="number" class="form-control" placeholder=" 00.000.000/0001-00" name="cnpj" id="cnpj"></label> 
    </fieldset> 
    </div> 
    <input name="submit" type="submit" value="Submit!"> 
</form> 

JS驗證:

$("#registerform").validate({ 
    rules: { 
    cpf: { 
     required: "#fis:checked" 
    }, 
    cnpj: { 
     required: "#jur:checked" 
    } 
    } 
}); 

回答

0

required方法需要返回true的領域是必要的。 所以,你可以簡單地傳遞一個函數required這將檢查radio元素checked

required method

需要(依賴回調)

類型:Function()

該函數與eleme一起執行nt,因爲它只是參數:如果它返回true,則該元素是必需的。

$("#registerform").validate({ 
    debug: true, 
    rules: { 
    cpf: { 
     required: function(elem) { 
     return $('#fis').is(":checked") 
     } 
    }, 
    cnpj: { 
     required: function(elem) { 
     return $('#jur').is(":checked") 
     } 
    } 
    } 
}); 

退房的-- JSFiddle Example --這裏。

+0

好吧,那是尷尬。哈哈感謝的人,它工作得很好 –