Use Javascript To Disable Submit Button Until Input Fields Are Filled In

How to disable your form submit button until all input fields are completed.

So, form validation can be a real bitch. Whether you are battling spam or simply trying to guide the user to properly fill out your form. In this short tutorial we are going to add an extra layer of client-side validation protection by disabling the form submit button until all of the input fields that we deem required are filled in.

Don’t Set Your Expectations Too High

This clever little trick delivered through pure Javascript with a splash of a CSS class won’t do much for spam protection. On another note, it does a great job in guiding your users to complete the form without missing important fields.

Step 1 – The Beautifully Simple, Pure Javascript Code

In short, this code does two things: First it runs a scan of your input form fields with a specific class, second, it disables the form submit button until there is information populated. Here is the Javascript code that can be placed in your <head> section:

	 function enableSubmit(){
   let inputs = document.getElementsByClassName('required'); // Enter your class name for a required field, this should also be reflected within your form fields.
   let btn = document.querySelector('input[type="submit"]');
   let isValid = true;

   for (var i = 0; i < inputs.length; i++){
     let changedInput = inputs[i];
     if (changedInput.value.trim() === "" || changedInput.value === null){
       isValid = false;
   btn.disabled = !isValid;

Step 2 – Your HTML Form Code

You don’t have to do much to your form code to bring the functionality to life. You will simply be adding a specific class to your input fields, in this case it’s class=”required” as well as a onkeyup event, which in this case looks like onkeyup=”enableSubmit()”. Lastly, you will want to add disabled to your submit button code to ensure that the button is not functional by default. Here is what the sample form code looks like:

<form action="#" method="post">
  <input type="text" class="required" onkeyup="enableSubmit()">
  <input type="text" class="required"  onkeyup="enableSubmit()">
  <input type="submit" value="Submit Form" disabled>

That’s all there is to it! Your form submit button will be disabled until the user fills in the appropriate input fields. You can now duplicate the input fields to create as many required fields that are needed on your form.