Set the html required attribute using JavaScript
In this tutorial, we are going to learn about how to set the html required attribute to the input element using JavaScript.
Consider, we have a following input
element in our html.
<input placeholder="Name" id="name"/>
Now, we need to set the required attribute to the above element.
To set the required atrribute to a html input element, first we need to access it inside the JavaScript by using the document.getElementById()
method.
const input = document.getElementById("name");
Now, it has a required
property by using that we can set the required attribute to the element.
input.required = true;
Note: required attribute is a boolean attribute.
To remove it from the element, set false
to the required
property.
input.required = false;