Home > Enterprise >  How to change value of Submit form button only if all required fields of the form are filled in (JS)
How to change value of Submit form button only if all required fields of the form are filled in (JS)

Time:09-25

I want to change the value of submit form button to "Loading..." with JAVA SCRIPT only if all the required fields in the form are filled in. Please help. Thank you!!!

<form>
    <div>
        <input id="my-file" name="my-file" type="file" accept="image/png, image/gif, image/jpeg" required>
    </div>
    <div>
        <input type="email" value="" name="my_email" required>
    </div>
    <div>
        <input id="visible_submit" type="submit" value="Submit">
    </div>
</form>
<script type="text/javascript">
var mySubmit = document.getElementById("visible_submit");
mySubmit.onclick = function addLoading() { document.getElementById("visible_submit").setAttribute("value", "Loading...");};

CodePudding user response:

Instead of listening for the click event on the submit button, listen for the submit event on the form.

Use checkValidity() to check whether the user has filled all the required fields, and Event.preventDefault() to prevent form submission:

var mySubmit = document.getElementById("visible_submit");
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {
  if (form.checkValidity()) {
    document.getElementById("visible_submit").value = "Loading...";
  }
  e.preventDefault();
})
<form>
  <div>
    <input id="my-file" name="my-file" type="file" accept="image/png, image/gif, image/jpeg" required>
  </div>
  <div>
    <input type="email" value="" name="my_email" required>
  </div>
  <div>
    <input id="visible_submit" type="submit" value="Submit">
  </div>
</form>

  • Related