Home >Web Front-end >JS Tutorial >How to Dynamically Set HTML5 Required Attribute Using Javascript
To dynamically set the required attribute in HTML5 using Javascript, follow the steps below:
Attempting to set the required attribute using the recommended W3C syntax:
document.getElementById("edName").attributes["required"] = "";
doesn't trigger validation checks.
The correct way to set an HTML5 validation boolean attribute is to use the element.required property.
For example:
document.getElementById("edName").required = true;
where edName is the ID of the input element.
In HTML5, boolean attributes can be defined either by:
However, when the required attribute is defined in the markup, the attribute's value is neither of these options:
edName.attributes.required = [object Attr]
This is because required is a reflected property, similar to id, name, and type.
Reflected properties are attributes that exist on the element object itself. Setting the value of a reflected property updates the corresponding attribute in the HTML.
Therefore, the following two methods are equivalent:
Using setter property:
element.required = true;
Using setAttribute:
element.setAttribute("required", "");
To clear a reflected property, use removeAttribute:
element.removeAttribute("required");
The above is the detailed content of How to Dynamically Set HTML5 Required Attribute Using Javascript. For more information, please follow other related articles on the PHP Chinese website!