从表单提交的输入字段中删除必需的属性

新手上路,请多包涵

模型:

 [Display(Name = "City"]
[Required]
[RegularExpression(@"^(?!\d$).*$"]
[StringLength(20,MinimumLength = 2]
public string City { get; set; }

形式:

 @Html.LabelFor(x => x.City, new { @class = "control-label" })
@Html.TextBoxFor(x => x.City, new {id="city" })

脚本:

 <script>
  $(document).ready(function () {
    $("#identificationForm").submit(function (e) {
      var required=document.getElementById("city").required;
      console.log(required);
      // e.preventDefault();
     });
  });
</script>

如果满足某些条件,我想删除所需的属性。无法以这种方式执行此操作。我该如何实现?

原文由 user2137186 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 900
2 个回答

JavaScript 区分大小写。

利用

document.getElementById("city").required = false;

示范

请注意,当您尝试在元素存在之前访问该元素时,您的代码将无法正常工作。如果您不在事件上执行代码,请将脚本放在元素之后:

 <input type="text" id="city" required>
<script>
if(somecondition is true){
    document.getElementById("city").required = false;
}
</script>

另请注意,您不能在提交函数中更改此设置并期望您的表单被提交,因为为时已晚:如果未填写必填字段,则不会调用此事件处理程序!

原文由 Denys Séguret 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以使用:

 document.getElementById("city").removeAttribute("required");

或者使用 jQuery

 $('#city').removeAttr('required')

原文由 j08691 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题