How to make input required in JavaScript

Sometimes we want to dynamically change the specific input to required.

Here’s how to do this with JavaScript:

Use the setAttribute() method.

yourElement.setAttribute("required", "");

Example:

<form>
  <input type="text" id="myInput">
  <input type="submit">
</form>

<script>
  document.getElementById('myInput').setAttribute("required", "");
</script>

Output (try to click submit with the empty input):