如何在Javascript中设置HTML5所需的属性? [英] How to set HTML5 required attribute in Javascript?

查看:109
本文介绍了如何在Javascript中设置HTML5所需的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Javascript中将 text 输入框标记为 required

 < input id =edNametype =textid =name> 

如果该字段最初标记为 required

 < form> 
< input id =edNametype =textid =namerequired>< br>
< input type =submitvalue =搜索>
< / form>

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



<但是现在我想通过Javascript在runtime中设置所需的属性:

 < form> 
< input id =edNametype =textid =name>< br>
< input type =submitvalue =搜索>
< / form>

加上相应的脚本:

  //推荐用于布尔属性的W3C HTML5语法
document.getElementById(edName)。attributes [required] =;

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



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



jsFiddle



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



HTML5验证 <$将c $ c> required 属性记录为布尔值:


4.10.7.3.4 必填 属性



必填 属性是布尔属性。指定时,元素是必需的。


关于如何定义,有很多令人费解的事情boolean 属性。 HTML5规范指出:


元素上布尔属性的存在表示真值,缺少属性表示false值。

如果该属性存在,它的值必须是空字符串或是属性规范名称的ASCII不区分大小写匹配的值,其中no领先或尾随空格。


这意味着您可以指定 required boolean 属性有两种不同的方式:

  edName.attributes.required =; //空字符串
edName.attributes.required =required; //属性的规范名称



但属性的真正值



当您查看我的jsFiddle这个问题时,你会发现如果在标记中定义所需的属性:

 < input id =edNametype =textid =namerequired> 

然后,该属性的值是 not 空字符串,也不是属性的规范名称:

  edName.attributes.required = [object Attr] 

这可能会导致解决方案。

解决方案

短版



  element.setAttribute(required,); //在
转动需要element.required = true; //需要通过反射属性
jQuery(element).attr('required',''); //需要
$(#elementId)。attr('required',''); //需要

element.removeAttribute(required); //需要关闭
element.required = false; //通过反射属性
jQuery(element).removeAttr('required'); //需要关闭
$(#elementId)。removeAttr('required'); //需要关闭

if(edName.hasAttribute(required){} //检查是否需要
if(edName.required){} //检查是否需要使用反射属性



长版



一旦TJ Crowder管理好指出反映了属性,我知道以下语法是错误的

  element.attributes [name] = value; // bad!覆盖HtmlAttribute对象
element.attributes.name = value; // bad!覆盖HtmlAttribute对象
value = element.attributes.name; // bad!返回HtmlAttribute对象,而不是它的值
value = element。 attributes [name]; // bad!返回HtmlAttribute对象,而不是其值

必须 通过 element.getAttribute element.setAttribute

  element.getAttribute( foo 的); //正确
element.setAttribute(foo,test); //正确

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

  element.attributes [foo]; //返回HtmlAttribute对象,而不是属性的值
element.attributes.foo; //返回HtmlAttribute对象,而不是属性的值

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

  element.attributes [foo] =true; //错误,因为true不是HtmlAttribute对象
element.setAttribute(foo,true); //错误,因为true不是HtmlAttribute对象

从概念上讲,正确的想法语言)是:

  HtmlAttribute属性=新的HtmlAttribute(); 
attribute.value =;
element.attributes [required] = attribute;

这就是为什么:


  • getAttribute(name)

  • setAttribute(name,value)
  • 存在


。他们完成了将值分配给HtmlAttribute对象的工作。



除此之外,还有一些属性反映。这意味着你可以在Javascript中更好地访问它们:

  //设置所需的属性
//元素。 setAttribute(required,);
element.required = true;

//检查属性
if(element.getAttribute(required)){...}
if(element.required){...}

//删除所需的属性
//element.removeAttribute(\"required);
element.required = false;

要做的是错误地使用 .attributes collection:

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



测试用例



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

 的document.getElementById( 名称)所需的。 
document.getElementById(name)。getAttribute(required);

结果:

  HTML .required .getAttribute(required)
========================== ==== =========== =========================
< input> false(布尔值)null(对象)
<输入必需> true(布尔)(字符串)
< input required => true(布尔)(字符串)
< input required =required> true(布尔值)required(字符串)
< input required =true> true(布尔值)true(字符串)
< input required =false> true(布尔值)false(字符串)
< input required =0>尝试访问。true(布尔型)0(字符串)

属性直接收集错误。它返回表示DOM属性的对象:

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

这解释了为什么您不应该与 .attributes 直接收集。您不是操纵属性的,而是操纵属性本身的对象。



如何设置required?



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

 元素。 setAttribute(required,); //更正
edName.required = true; //正确的

严格地说,任何其他值都会设置属性。但布尔属性的定义规定,它只能设置为空字符串来表示。以下方法都可用于设置 所需的 布尔属性,

不使用

  element.setAttribute(required,需要); //有效,但不是首选
element.setAttribute(required,foo); //工作,但很傻
element.setAttribute(required,true); //工作,但不这样做,因为:
element.setAttribute(required,false); //将所需的布尔值设置为true
element.setAttribute(required,false); //还将必需的布尔值设置为true
element.setAttribute(required,0); //也将所需的布尔值设置为true

我们已经知道直接设置属性是错误的:

  edName.attributes [required] = true; //错误
edName.attributes [required] =; //错误
edName.attributes [required] =required; //错误
edName.attributes.required = true; //错误
edName.attributes.required =; //错误
edName.attributes.required =required; //错误



如何清除必需?



尝试删除所需的属性时的技巧是容易意外地打开它:

  edName.removeAttribute(required); //改正
edName.required = false; //正确

使用无效的方式:

  edName.setAttribute(required,null); //错误!实际上需要转! 
edName.setAttribute(required,); //错误!实际上需要打开!
edName.setAttribute(required,false); //错误!实际上需要打开!
edName.setAttribute(required,false); //错误!实际上需要打开!
edName.setAttribute(required,0); //错误!实际上需要打开!

使用反映的 .required 属性时,您还可以使用任何falsey值将其关闭,并使用truthy值将其打开。但为了清晰起见,只需坚持真假。



如何为检查所需的



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

  if(edName.hasAttribute(required)
{
}

您也可以通过布尔来检查它是否反映了 .required property:

  if(edName.required)
{
}


I am trying to mark a text input box as required in Javascript.

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

If the field is initially marked as 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:

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

<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 correct way to set an HTML5 validation boolean attribute?

jsFiddle

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

The HTML5 validation required attribute is documented as a Boolean:

4.10.7.3.4 The required attribute

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

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

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.

This means that you can specify a required boolean attribute two different ways:

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 required attribute is defined in the markup:

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

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

edName.attributes.required = [object Attr]

That might lead to a solution.

解决方案

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:

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 must go through element.getAttribute and element.setAttribute:

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

This is because the attribute actually contains a special HtmlAttribute object:

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 String object, rather than the HtmlAttribute object it requires:

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)

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

On top of this, some attribute are reflected. This means that you can access them more nicely from 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't want to do is mistakenly use the .attributes collection:

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 required attribute, comparing the values returned through the attribute, and the reflected property

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 .attributes collection directly is wrong. It returns the object that represents the DOM attribute:

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

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

How to set required?

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

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

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

but do not use them:

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

The trick when trying to remove the required attribute is that it's easy to accidentally turn it on:

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 .required property, 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.

How to check for required?

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

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

You can also check it through the Boolean reflected .required property:

if (edName.required)
{
}

这篇关于如何在Javascript中设置HTML5所需的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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