[英]How can I a field as required based on selection of radio button in a form
There is a custom radio button.有一个自定义单选按钮。 On select of 'yes' of that button another field is there which should not be required在选择该按钮的“是”时,另一个字段不应该是必需的
$("#btnFormSubmit").click(function() {
var radioValue = $("input[name='CustomDuration']:checked").val();
if (radioValue == 'Yes') {
$("#frmCertificateRequirement").validate({
rules: {
ValidDurationMonths: {
required: false
}
}
})
}
Firstly you need to call validate()
when the page loads, not when the submit button of the form is clicked.首先,您需要在页面加载时调用validate()
,而不是在单击表单的提交按钮时调用。
With regards to your issue, the required
property will accept a selector you can use to dynamically set the validation requirements for the element.关于您的问题, required
属性将接受一个选择器,您可以使用它来动态设置元素的验证要求。 Try this:尝试这个:
$("#frmCertificateRequirement").validate({
rules: {
ValidDurationMonths: {
required: 'input[name="CustomDuration"]:checked'
}
}
});
If you do not want to show the Required Message when the radio button is checked .如果您不想在选中单选按钮时显示所需消息。 Then There is no closing of your code , please correct it.那么您的代码没有关闭,请更正。
HTML Code HTML代码
<form name="btnFormSubmit" id="btnFormSubmit" method="post">
<div>
<label for="username">Username/Email</label>
<input type="text" name="username" autocomplete="false" readonly onfocus="this.removeAttribute('readonly');">
</div>
<button type="submit" id="btnFormSubmit">submit</button>
</form>
<input type="checkbox" name="CustomDuration" id="CustomDuration" value="Yes">checkbox
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
JQUERY Code with perfect closing具有完美关闭的 JQUERY 代码
$("#btnFormSubmit").click(function () {
var radioValue = $('input[name="CustomDuration"]:checked').val();
if (radioValue == "Yes") {
$("#login_form").validate({
rules:{
username:
{
required: false,
}
},
});
}
}); /*You have missing this closing*/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.