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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18111915/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 21:03:00  来源:igfitidea点击:

remove required property from input field on form submit

javascriptjqueryhtmlasp.net-mvc-4

提问by user2137186

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?

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

回答by Denys Séguret

JavaScript is case sensitive.

JavaScript 区分大小写。

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 !

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

回答by j08691

You can use:

您可以使用:

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

or with jQuery

或使用 jQuery

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

回答by Fals

You shoud do this:

你应该这样做:

if(somecondition is true)
{
  var city = document.getElementById("city");
  city.removeAttribute('required');
}

回答by rasmicah

By the time the On Submitfunction is to remove the required attribute, the form would have already passed validation. The steps are first you have to disable validation then you will be able to submit the form with the required fields empty. Next remove the required attributes and finally manually invoke validation via $.validator.unubtrusive.parse(form)and this will now validate the form by invoking the other validation types such as string lengthand formatting, everything else except the required attributes. Check if form.valid() then submit() elsedo nothing.

On Submit函数删除所需的属性时,表单已经通过了验证。步骤是首先您必须禁用验证,然后您将能够提交带有空的必填字段的表单。接下来删除所需的属性,最后手动调用验证通过$.validator.unubtrusive.parse(form),现在这将通过调用其他验证类型(例如string length和)来验证表单,formatting除了必需的属性之外的所有其他内容。检查if form.valid() then submit() else什么都不做。

回答by Sarfaraz Ansari

In php its very easy, this will not validate your form while submitting,

在 php 中它很容易,这不会在提交时验证您的表单,

<input type="submit" onclick="return confirm('Are you sure?')" value="Abort Test" formnovalidate>

回答by Sean Ciminello

Not sure if anyone has figured out a better way to do this yet and it might not be the most efficient way to do it but you could use PHP to get this done. If the condition you are looking to meet is known before the page loads then you can have this:

不确定是否有人已经找到了更好的方法来做到这一点,这可能不是最有效的方法,但您可以使用 PHP 来完成这项工作。如果您希望满足的条件在页面加载之前已知,那么您可以使用:

<input type="text" id="city" 

<?php
     if (condition_is_met) {
          echo ">";
     } else {
          echo "required>";
     }
?>

回答by S. Mayol

If you put your text fields in a form, it is possible to overwrite the required field with a special attribute called novalidate. This is the syntax: <form novalidate> .. </form>

如果您将文本字段放在表单中,则可以使用名为novalidate的特殊属性覆盖必填字段。这是语法:<form novalidate> .. </form>

Here is an example:

下面是一个例子:

<form novalidate>
  Zip code: <input type="text" name="zipcode" pattern="[0-9]{5}" required><br/>

  <input type="submit">
</form>

The novalidate AttributeHere is a link with two live demos using novalidateattribute.

novalidate 属性这是一个链接,其中包含两个使用novalidate属性的现场演示。

回答by Edison Neza

Or in the moment that form is submitted you can disabled it if it's null:

或者在提交表单的那一刻,如果它为空,您可以禁用它:

if($("#City").val().trim().length == 0) $("#City").attr("disabled", true);

if($("#City").val().trim().length == 0) $("#City").attr("disabled", true);