Development Tip

Javascript에서 HTML5 필수 속성을 설정하는 방법은 무엇입니까?

yourdevel 2020. 10. 25. 13:10
반응형

Javascript에서 HTML5 필수 속성을 설정하는 방법은 무엇입니까?


Javascript에서 text입력 상자를 필수 로 표시하려고합니다 .

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

필드가 처음에 다음으로 표시되는 경우 required:

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

사용자가 제출을 시도하면 유효성 검사 오류가 발생합니다.

여기에 이미지 설명 입력

하지만 이제 Javascript를 통해 "runtime"required 속성 을 설정하고 싶습니다 .

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

해당 스크립트로 :

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

지금 제출할 때를 제외하고는 유효성 검사 나 차단이 없습니다.

HTML5 유효성 검사 부울 속성 을 설정하는 올바른 방법 은 무엇입니까 ?

jsFiddle

속성의 가치는 무엇입니까?

HTML5 유효성 검사 required속성은 다음 과 같이 문서화 됩니다 Boolean.

4.10.7.3.4 required속성

required속성은이다 부울 속성 . 지정된 경우 요소가 필요합니다.

boolean속성 을 정의하는 방법에 대해 많은 수작업이 있습니다. HTML5 사양 노트 :

요소에 부울 속성이 있으면 참 값을 나타내고 속성이 없으면 거짓 값을 나타냅니다.

속성이있는 경우 해당 값은 선행 또는 후행 공백없이 속성의 표준 이름에 대해 ASCII 대소 문자를 구분하지 않는 일치 값이거나 빈 문자열이어야합니다.

이는 required 부울 속성을 두 가지 다른 방법으로 지정할 수 있음을 의미합니다 .

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

그러나 실제로 속성의 가치는 무엇 입니까?

이 문제의 jsFiddle 을 보면 required속성이 마크 업에 정의되어 있는지 알 수 있습니다 .

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

그런 다음 속성의 값이 없는 빈 문자열이나 속성의 정식 이름은 :

edName.attributes.required = [object Attr]

그것은 해결책으로 이어질 수 있습니다.


requiredA는 반사 속성 (같은 id, name, type, 등), 너무 :

element.required = true;

... element실제 inputDOM 요소 어디에 있습니까? 예 :

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

(완전 함을 위해.)

레:

그러면 속성 값은 빈 문자열도 아니고 속성의 정식 이름도 아닙니다.

edName.attributes.required = [object Attr]

required코드 에서 문자열 이 아니라 속성 객체 이기 때문 입니다 . attributesA는 NamedNodeMap, 값이 Attr개체 . 그들 중 하나의 가치를 얻으려면 그 value속성을 살펴볼 것 입니다. 그러나 부울 속성의 경우 값은 관련이 없습니다. 속성이 맵에 있거나 (true) 존재하지 않습니다 (false).

따라서 반영 required 되지 않은 경우 속성을 추가하여 설정합니다.

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

... 이는 element.required = true. 완전히 제거하여 지울 수 있습니다.

element.removeAttribute("required");

... 이는 element.required = false.

그러나 우리는 required그것을 반영하기 때문에 그것을 할 필요가 없습니다 .


짧은 버전

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

긴 버전

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

당신은 해야한다 통과 element.getAttributeelement.setAttribute:

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

이는 속성에 실제로 특수 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

속성 값을 "true"로 설정 하면 필요한 HtmlAttribute 개체가 아닌 String 개체 로 실수로 설정하는 것입니다 .

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

개념적으로 올바른 아이디어 (유형화 된 언어로 표현됨)는 다음과 같습니다.

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

이는 이유:

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

있다. 내부의 HtmlAttribute 개체에 값을 할당하는 작업을 수행합니다.

여기에 일부 속성이 반영됩니다 . 즉, 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)
{
}

And the jquery version:

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

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


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

You can set it using

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

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.


try out this..

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

참고 URL : https://stackoverflow.com/questions/18770369/how-to-set-html5-required-attribute-in-javascript

반응형