Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
316 views
in Technique[技术] by (71.8m points)

javascript - remove required property from input field on form submit

Model:

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

Form:

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

Script:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

JavaScript is case sensitive.

Use

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

Demonstration

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>

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 !


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...