![](/img/trans.png)
[英]Jquery validation if checkbox checked text box gets class=“form-input validate required”
[英]JQuery validation-input text field to be required if checkbox checked
我有以下復選框:
<input type="checkbox" id="startClientFromWeb" name="startClientFromWeb" data-bind="checked: StartClientFromWeb" />
以及以下輸入文本字段:
<input id="mimeType" name="mimeType" data-bind= "value: MimeType" />
這是我的 js 驗證代碼:
$("#franchiseForm").validate({
rules: {
mimeType: {
required: $("#startClientFromWeb").is(":checked")
}
}
});
我希望只有在選中復選框時才需要 mimeType 輸入文本字段。 由於某種原因,上述方法不起作用。 我對 javascript 和 jquery 很陌生。 任何有關工作示例的幫助將不勝感激。 謝謝!
您可以添加自己的自定義驗證方法來處理這樣的事情:
$.validator.addMethod("requiredIfChecked", function (val, ele, arg) {
if ($("#startClientFromWeb").is(":checked") && ($.trim(val) == '')) { return false; }
return true;
}, "This field is required if startClientFromWeb is checked...");
$("#franchiseForm").validate({
rules: {
mimeType: { requiredIfChecked: true }
}
});
如果disabled
輸入,則不會觸發驗證。 您可以使用該事實 - 讓文本框成為必需,但最初被禁用,並且僅在復選框被選中時啟用它。
$(function () {
$('#startClientFromWeb').change(function () {
if ($(this).is(':checked')) {
$('#mimeType').removeAttr('disabled');
}
else {
$('#mimeType').attr('disabled', 'disabled');
}
});
});
最簡單的工作方式:
rules : {mimeType:{required:"#startClientFromWeb:checked"}}, messages: {mimeType: {required: 'Repeat checked, To date required'}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.