[英]when one field is filled other fields must be required
I created a form.In that i added validations.if one field in the form is filled,all other fields must be filled or if none of the fields are filled then no need of checking validations. 我创建了一个表单。在其中添加了验证。如果表单中的一个字段被填充,则所有其他字段都必须被填充,或者如果所有字段都不被填充,则无需检查验证。 Iam using a method focus to add validations.once selecting a field,all fields are required validation executing.
我使用方法焦点来添加验证。选择一个字段后,所有字段都需要执行验证。
iam using jquery-validation IAM使用jQuery验证
<script>
$(document).ready(function () {
$("#myFormId").validate(
{
}
);
$('.contact1').focus(function () {
$('.contact1').addClass("required");
});
$('.contact2').focus(function () {
$('.contact2').addClass("required");
});
});
</script>
when i clicking on the field required is adding to field.how to remove required if no field is filled in the form 当我单击所需的字段时,将添加到field.how如果表单中未填写任何字段,则需要删除
$('#myFormId').on('change', function() { // change or input event var $inputs = $(this).find(':input:not(:submit)'); var anyInputChanged = !!$inputs.filter(function() { return this.value !== this.defaultValue; }).length; $inputs.toggleClass('required', anyInputChanged); });
.required { outline: 1px solid red; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <form id="myFormId"> <input> <input> <input type="submit"> </form>
You could toggle required class if any input in form has no more its default value: 如果表单中的任何输入不再具有其默认值,则可以切换所需的类:
$('#myFormId').on('change', function() { // change or input event
var $inputs = $(this).find(':input:not(:submit)');
var anyInputChanged = !!$inputs.filter(function() {
return this.value !== this.defaultValue;
}).length;
$inputs.toggleClass('required', anyInputChanged);
});
You're code doesn't quite match up with what you want to do, it could look more like this: 您的代码与您要执行的操作不太匹配,看起来可能更像这样:
<script>
$(document).ready(function () {
$("#myFormId").validate(
{
...
}
);
$('#myFormId input').on('focus keyup', function() {
if($(this).val().length > 0){
$('#myFormId input').attr("required",true);
}
else{
$('#myFormId input').attr("required",false);
}
});
});
</script>
Also, you may need to re-call the validate function on the form when you alter the attributes (but don't quote me on that). 另外,更改属性时,您可能需要在表单上重新调用validate函数(但不要在其上引用我)。
This should be closer to what you want, but have a play around! 这应该更接近您想要的东西,但是可以玩一玩!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.