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:
Reference:
JavaScript setAttribute() reference
Share "How to set the required attribute in JavaScript?"
Related snippets:
- Create HTML element with attributes in JavaScript
- Get element by ID in React
- Set the required attribute in JavaScript
- Get elements by data attribute in JavaScript
- Add class to the clicked element in JavaScript
- Add class to multiple elements in JavaScript
- Add class to element if it does not already exists with JavaScript
- Add data attribute to element in JavaScript
- Add CSS class to body with JavaScript
- Add class to parent element in JavaScript
- Toggle fullscreen and normal mode with JavaScript
- Play video in fullscreen with vanilla JavaScript
- Select HTML elements by CSS selectors in vanilla JavaScript
- Exit from fullscreen mode on click in JavaScript
- Switch browser to fullscreen mode with JavaScript
- Get the value of text input field in JavaScript
- Get element with data- attribute using vanilla JavaScript
- Get the value of selected radio button in JavaScript
- Get selected option from select using JavaScript
- Check if element is hidden in JavaScript
Tags:
set, add, remove, required, attribute, input, javascript Technical term:
Set the required attribute in JavaScript