Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove required property from input field on form submit

Tags:

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?

like image 573
user2137186 Avatar asked Aug 07 '13 19:08

user2137186


People also ask

How do I get rid of required attributes?

To remove the required attribute, select the element and call the removeAttribute() method on it, passing it required as a parameter, e.g. input. removeAttribute('required') . The removeAttribute method will remove the required attribute from the element.

How do you change the input field required?

The required attribute is a boolean attribute. When present, it specifies that an input field must be filled out before submitting the form. Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.

How do you make a field not required in HTML?

Just unset the required attribute. If you're trying to unset it after some user action (with javascript) then use the .


2 Answers

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 !

like image 59
Denys Séguret Avatar answered Sep 20 '22 10:09

Denys Séguret


You can use:

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

or with jQuery

$('#city').removeAttr('required') 
like image 42
j08691 Avatar answered Sep 20 '22 10:09

j08691