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

use*_*186 13 javascript jquery html5 asp.net-mvc-4

模型:

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

形成:

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

脚本:

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

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

Den*_*ret 32

JavaScript区分大小写.

使用

document.getElementById("city").required = false;
Run Code Online (Sandbox Code Playgroud)

示范

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

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

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


j08*_*691 10

您可以使用:

document.getElementById("city").removeAttribute("required");
Run Code Online (Sandbox Code Playgroud)

或者使用jQuery

$('#city').removeAttr('required')
Run Code Online (Sandbox Code Playgroud)


Fal*_*als 5

您应该这样做:

if(somecondition is true)
{
  var city = document.getElementById("city");
  city.removeAttribute('required');
}
Run Code Online (Sandbox Code Playgroud)