Home > Web Front-end > JS Tutorial > body text

How to Dynamically Set HTML5 Required Attribute Using Javascript

DDD
Release: 2024-10-20 22:37:30
Original
724 people have browsed it

How to Dynamically Set HTML5 Required Attribute Using Javascript

Setting HTML5 Required Attribute Dynamically Using Javascript

To dynamically set the required attribute in HTML5 using Javascript, follow the steps below:

Issue Overview

Attempting to set the required attribute using the recommended W3C syntax:

document.getElementById("edName").attributes["required"] = "";
Copy after login

doesn't trigger validation checks.

Correct Way to Set HTML5 Validation Boolean Attribute

The correct way to set an HTML5 validation boolean attribute is to use the element.required property.

For example:

document.getElementById("edName").required = true;
Copy after login

where edName is the ID of the input element.

Understanding the Attribute Value

In HTML5, boolean attributes can be defined either by:

  • Leaving the attribute empty: required=""
  • Using the attribute's canonical name: required="required"

However, when the required attribute is defined in the markup, the attribute's value is neither of these options:

edName.attributes.required = [object Attr]
Copy after login

This is because required is a reflected property, similar to id, name, and type.

Reflected Properties

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;
Copy after login

Using setAttribute:

element.setAttribute("required", "");
Copy after login

To clear a reflected property, use removeAttribute:

element.removeAttribute("required");
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template