- Instant help with your JavaScript coding problems

Set the required attribute in JavaScript

How to set the required attribute in JavaScript?
inputField.setAttribute("required", true);

To set the required attribute on a HTML input element you can use the setAttribute() method on the element.

Let's suppose the following HTML code:

    <input type="text" name="name" id="name" placeholder="Enter your name" />
    <input type="submit" value="Submit" />

Adding the required attribute dinamically with a JavaScript code looks like this:

document.addEventListener('DOMContentLoaded', function() {
    const nameField = document.getElementById("name");   
    nameField.setAttribute("required", true);

And the result when submitting the empty field looks like this:

Add required attribute to an input field

Share "How to set the required attribute in JavaScript?"