- Instant help with your JavaScript coding problems

Set the required attribute in JavaScript

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

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:

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

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?"