从表单提交的输入字段中删除必需的属性 [英] remove required property from input field on form submit

查看:179
本文介绍了从表单提交的输入字段中删除必需的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

型号:

[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>

我想在满足某些条件的情况下删除必需的属性.无法通过这种方式进行操作.

I want to remove required property if some condition is met.Unable to do this this way.How can i achieve this?

推荐答案

JavaScript区分大小写.

JavaScript is case sensitive.

使用

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

演示

请小心,因为您尝试在元素存在之前对其进行访问,因此代码无法正常工作.如果您不对事件执行代码,则将脚本放在元素之后:

Be careful that your code can't work as you try to access the element before it exists. Put your script after the element if you don't execute the code on an event :

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

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

Note also that you can't change this in a submit function and expect your form to be submitted because it's too late : this event handler won't be called if the required field is not filled !

这篇关于从表单提交的输入字段中删除必需的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆