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");
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3