Html 如何在 Javascript 中设置 HTML5 必需属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18770369/
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-29 13:21:10  来源:igfitidea点击:

How to set HTML5 required attribute in Javascript?

javascripthtmlvalidation

提问by Ian Boyd

I am trying to mark a textinput box as requiredin Javascript.

我正在尝试根据Javascript 的要求标记text输入框。

<input id="edName" type="text" id="name">

If the field is initially marked as required:

如果该字段最初标记为required

<form>
    <input id="edName" type="text" id="name" required><br>
    <input type="submit" value="Search">
</form>

when the user tries to submit they are given a validation error:

当用户尝试提交时,他们会收到验证错误:

enter image description here

在此处输入图片说明

But now I want to set the requiredattribute at "runtime", through Javascript:

但现在我想通过 Javascriptrequired"runtime"设置属性:

<form>
    <input id="edName" type="text" id="name"><br>
    <input type="submit" value="Search">
</form>

with the corresponding script:

使用相应的脚本:

//recommended W3C HTML5 syntax for boolean attributes
document.getElementById("edName").attributes["required"] = "";         

Except when I submit now, there is no validation check, no block.

除了我现在提交时,没有验证检查,没有阻止。

What is the correctway to set an HTML5 validation boolean attribute?

设置HTML5 验证布尔属性正确方法是什么?

jsFiddle

js小提琴

What's the value of the attribute, you ask?

你问这个属性的值是什么?

The HTML5 validation requiredattribute is documentedas a Boolean:

HTML5 验证required属性记录Boolean

4.10.7.3.4 The requiredattribute

The requiredattribute is a boolean attribute. When specified, the element is required.

4.10.7.3.4required属性

required属性是一个布尔属性。指定时,该元素是必需的。

There is a lot of hand-wringing about how to define a booleanattribute. The HTML5 spec notes:

关于如何定义boolean属性有很多麻烦。HTML5 规范指出:

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

元素上布尔属性的存在表示真值,不存在该属性表示假值。

如果该属性存在,则其值必须是空字符串,或者是与该属性的规范名称不区分大小写的 ASCII 匹配值,且没有前导或尾随空格。

This means that you can specify a requiredbooleanattribute two different ways:

这意味着您可以通过两种不同的方式指定required布尔属性:

edName.attributes.required = ""; //the empty string
edName.attributes.required = "required"; //the attribute's canonical name

But what is the value of the attribute really?

但是,什么是属性的值真的

When you look at my jsFiddle of this problem, you'll notice that if the requiredattribute is defined in the markup:

当您查看我关于此问题的 jsFiddle 时,您会注意到,如果required在标记中定义了该属性:

<input id="edName" type="text" id="name" required>

Then the attribute's value is notthe empty string, nor the canonical name of the attribute:

那么属性的值不是空字符串,也不是属性的规范名称:

edName.attributes.required = [object Attr]

That might lead to a solution.

这可能会导致解决方案。

回答by T.J. Crowder

requiredis a reflected property(like id, name, type, and such), so:

required反射属性(如idnametype等),因此:

element.required = true;

...where elementis the actual inputDOM element, e.g.:

...element实际的inputDOM 元素在哪里,例如:

document.getElementById("edName").required = true;


(Just for completeness.)

(只是为了完整性。)

Re:

关于:

Then the attribute's value is not the empty string, nor the canonical name of the attribute:

edName.attributes.required = [object Attr]

那么属性的值不是空字符串,也不是属性的规范名称:

edName.attributes.required = [object Attr]

That's because requiredin that code is an attribute object, not a string; attributesis a NamedNodeMapwhose values are Attrobjects. To get the value of one of them, you'd look at its valueproperty. But for a boolean attribute, the value isn't relevant; the attribute is either present in the map (true) or not present (false).

那是因为required在该代码中是一个属性 object,而不是一个字符串;attributes是一个,NamedNodeMap其值为Attrobjects。要获得其中之一的价值,您需要查看其value属性。但是对于布尔属性,该值是不相关的;该属性在地图中存在 (true) 或不存在 (false)。

So if requiredweren'treflected, you'd set it by adding the attribute:

因此,如果required没有反映,您可以通过添加属性来设置它:

element.setAttribute("required", "");

...which is the equivalent of element.required = true. You'd clear it by removing it entirely:

...相当于element.required = true. 您可以通过完全删除它来清除它:

element.removeAttribute("required");

...which is the equivalent of element.required = false.

...相当于element.required = false.

But we don't have to do that with required, since it's reflected.

但是我们不必对 这样做required,因为它被反射了。

回答by Ian Boyd

Short version

精简版

element.setAttribute("required", "");    //turns required on
element.required = true;                 //turns required on through reflected attribute
jQuery(element).attr('required', '');    //turns required on
$("#elementId").attr('required', '');    //turns required on

element.removeAttribute("required");     //turns required off
element.required = false;                //turns required off through reflected attribute
jQuery(element).removeAttr('required');  //turns required off
$("#elementId").removeAttr('required');  //turns required off

if (edName.hasAttribute("required")) { }  //check if required
if (edName.required) { }                 //check if required using reflected attribute

Long Version

长版

Once T.J. Crowder managed to point out reflected properties, i learned that following syntax is wrong:

一旦 TJ Crowder 设法指出反射属性,我了解到以下语法是错误的

element.attributes["name"] = value; //bad! Overwrites the HtmlAttribute object
element.attributes.name = value;    //bad! Overwrites the HtmlAttribute object
value = element.attributes.name;    //bad! Returns the HtmlAttribute object, not its value
value = element.attributes["name"]; //bad! Returns the HtmlAttribute object, not its value

You mustgo through element.getAttributeand element.setAttribute:

必须通过element.getAttributeelement.setAttribute

element.getAttribute("foo");         //correct
element.setAttribute("foo", "test"); //correct

This is because the attribute actually contains a special HtmlAttributeobject:

这是因为该属性实际上包含一个特殊的HtmlAttribute对象:

element.attributes["foo"];           //returns HtmlAttribute object, not the value of the attribute
element.attributes.foo;              //returns HtmlAttribute object, not the value of the attribute

By setting an attribute value to "true", you are mistakenly setting it to a Stringobject, rather than the HtmlAttributeobject it requires:

通过将属性值设置为“true”,您错误地将其设置为String对象,而不是它所需的HtmlAttribute对象:

element.attributes["foo"] = "true";  //error because "true" is not a HtmlAttribute object
element.setAttribute("foo", "true"); //error because "true" is not an HtmlAttribute object

Conceptually the correct idea (expressed in a typed language), is:

从概念上讲,正确的想法(用类型语言表达)是:

HtmlAttribute attribute = new HtmlAttribute();
attribute.value = "";
element.attributes["required"] = attribute;

This is why:

这就是为什么:

  • getAttribute(name)
  • setAttribute(name, value)
  • getAttribute(name)
  • setAttribute(name, value)

exist. They do the work on assigning the value to the HtmlAttribute object inside.

存在。他们负责将值分配给内部的 HtmlAttribute 对象。

On top of this, some attribute are reflected. This means that you can access them more nicely from Javascript:

在此之上,反映了一些属性。这意味着您可以从 Javascript 更好地访问它们:

//Set the required attribute
//element.setAttribute("required", ""); 
element.required = true;

//Check the attribute
//if (element.getAttribute("required")) {...}
if (element.required) {...}

//Remove the required attribute
//element.removeAttribute("required");
element.required = false;

What you don'twant to do is mistakenly use the .attributescollection:

什么,你想要做的就是误用.attributes集合:

element.attributes.required = true;     //WRONG!
if (element.attributes.required) {...}  //WRONG!
element.attributes.required = false;    //WRONG!

Testing Cases

测试案例

This led to testing around the use of a requiredattribute, comparing the values returned through the attribute, and the reflected property

这导致围绕required属性的使用进行测试,比较通过属性返回的值和反射的属性

document.getElementById("name").required;
document.getElementById("name").getAttribute("required");

with results:

结果:

HTML                         .required        .getAttribute("required")
==========================   ===============  =========================
<input>                      false (Boolean)  null (Object)
<input required>             true  (Boolean)  "" (String)
<input required="">          true  (Boolean)  "" (String)
<input required="required">  true  (Boolean)  "required" (String)
<input required="true">      true  (Boolean)  "true" (String)
<input required="false">     true  (Boolean)  "false" (String)
<input required="0">         true  (Boolean)  "0" (String)

Trying to access the .attributescollection directly is wrong. It returns the object that represents the DOM attribute:

尝试.attributes直接访问集合是错误的。它返回代表 DOM 属性的对象:

edName.attributes["required"] => [object Attr]
edName.attributes.required    => [object Attr]

This explains why you should never talk to the .attributescollect directly. You're not manipulating the valuesof the attributes, but the objects that represent the attributes themselves.

这解释了为什么你永远不应该.attributes直接与收集者交谈。您不是在操纵属性的,而是在操纵代表属性本身的对象。

How to set required?

需要怎么设置?

What's the correct way to set requiredon an attribute? You have two choices, either the reflected property, or through correctly setting the attribute:

设置required属性的正确方法是什么?您有两种选择,要么是反射属性,要么是通过正确设置属性:

element.setAttribute("required", "");         //Correct
edName.required = true;                       //Correct

Strictly speaking, any other value will "set" the attribute. But the definition of Booleanattributes dictate that it should only be set to the empty string ""to indicate true. The following methods all work to setthe requiredBooleanattribute,

严格来说,任何其他值都会“设置”该属性。但是Boolean属性的定义规定它应该只设置为空字符串""以指示true。下面的方法都工作到设定required布尔属性,

but do not usethem:

不要使用它们:

element.setAttribute("required", "required"); //valid, but not preferred
element.setAttribute("required", "foo");      //works, but silly
element.setAttribute("required", "true");     //Works, but don't do it, because:
element.setAttribute("required", "false");    //also sets required boolean to true
element.setAttribute("required", false);      //also sets required boolean to true
element.setAttribute("required", 0);          //also sets required boolean to true

We already learned that trying to set the attribute directly is wrong:

我们已经了解到,尝试直接设置属性是错误的:

edName.attributes["required"] = true;       //wrong
edName.attributes["required"] = "";         //wrong
edName.attributes["required"] = "required"; //wrong
edName.attributes.required = true;          //wrong
edName.attributes.required = "";            //wrong
edName.attributes.required = "required";    //wrong

How to clearrequired?

需要怎么清除

The trick when trying to removethe requiredattribute is that it's easy to accidentally turn it on:

尝试删除required属性时的技巧是很容易不小心将其打开:

edName.removeAttribute("required");     //Correct
edName.required = false;                //Correct

With the invalid ways:

使用无效方式:

edName.setAttribute("required", null);    //WRONG! Actually turns required on!
edName.setAttribute("required", "");      //WRONG! Actually turns required on!
edName.setAttribute("required", "false"); //WRONG! Actually turns required on!
edName.setAttribute("required", false);   //WRONG! Actually turns required on!
edName.setAttribute("required", 0);       //WRONG! Actually turns required on!

When using the reflected .requiredproperty, you can also use any "falsey"values to turn it off, and truthy values to turn it on. But just stick to true and false for clarity.

使用反射.required属性时,您还可以使用任何“falsey”值将其关闭,并使用真值将其打开。但为了清楚起见,请坚持真假。

How to checkfor required?

如何检查required

Check for the presence of the attribute through the .hasAttribute("required")method:

通过.hasAttribute("required")方法检查属性是否存在:

if (edName.hasAttribute("required"))
{
}

You can also check it through the Booleanreflected .requiredproperty:

您还可以通过布尔反射.required属性进行检查 :

if (edName.required)
{
}

回答by vladCovaliov

And the jquery version:

和 jquery 版本:

$('input').attr('required', true)
$('input').attr('required', false)

I know it's beyond the question, but maybe someone will find this helpful :)

我知道这超出了问题的范围,但也许有人会发现这有帮助:)

回答by Denys Séguret

What matters isn't the attribute but the property, and its value is a boolean.

重要的不是属性而是property,它的值是一个布尔值。

You can set it using

您可以使用它进行设置

 document.getElementById("edName").required = true;

回答by Kyle Pennell

let formelems = document.querySelectorAll('input,textarea,select');
formelems.forEach((formelem) => {
  formelem.required = true;

});

If you wish to make all input, textarea, and select elements required.

如果您希望所有 input、textarea 和 select 元素都需要。

回答by Vijay

try out this..

试试这个..

document.getElementById("edName").required = true;