javascript 在 ASP MVC 中动态删除元素的必需属性?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31466002/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
dynamically remove an element's required attribute in ASP MVC?
提问by Mike
Is there a way, in an ASP MVC project using unobtrusive validation, to dynamically remove the Required attribute from an element?
在使用非侵入式验证的 ASP MVC 项目中,有没有办法从元素中动态删除 Required 属性?
The element is decorated with a Required annotation in the view model. I thought I could remove this by removing the html attribute, "data-val-required," with JQuery but client validation still treats the element as required. Is it impossible to manipulate the element's validation by manipulating the unobtrusive validation attributes?
该元素在视图模型中使用 Required 注释进行装饰。我想我可以通过使用 JQuery 删除 html 属性“data-val-required”来删除它,但客户端验证仍将元素视为必需的。是否无法通过操纵不显眼的验证属性来操纵元素的验证?
This is what I tried, but it didn't work. I wanted to remove the required attribute if a check box was unchecked.
这是我尝试过的,但没有奏效。如果未选中复选框,我想删除所需的属性。
$("#chkTempHire").click(function () {
var checked = $(this).attr("checked");
var attr = $("#txtTempHireEndDate").attr("data-val-required");
var hasAttr = false;
if (typeof attr !== typeof undefined && attr !== false)
hasAttr = true;
if (!checked && hasAttr)
$("#txtTempHireEndDate").removeAttr("data-val-required");
});
Am I missing something, or is it just not possible?
我错过了什么,还是不可能?
Thank you!
谢谢!
回答by Chris Roberts
You can use the .rules()
method built into jQuery, you don't need to manually remove attributes.
您可以使用.rules()
jQuery 内置的方法,不需要手动删除属性。
To remove:
去除:
$("#txtTempHireEndDate").rules("remove", "required")
To add:
添加:
$("#txtTempHireEndDate").rules("add", "required")
回答by chenZ
you can use rules function in jquery.validate
您可以在 jquery.validate 中使用规则功能
$("..").rules("add",....)
$("..").rules("remove",...)
回答by Ricardo Pontual
You must revalidate the form.
您必须重新验证表单。
Just call the validate function from form, like this:
只需从表单调用验证函数,如下所示:
$('#FormId').valid();
You can also validate the control you've removed the attribute:
您还可以验证已删除属性的控件:
$('#txtTempHireEndDate').valid();
回答by Meera
$("#dailyFlow").removeAttr('data-val-required');
$("#dailyFlow").removeAttr('data-val-required');