How to handle Submit button when the form changes?

This was one of my favorite process in my career. When I use forms, this will be the request from the clients, When the user changes something, then the submit button should be enabled. In Angular, this process was pretty easy, but in native javascript or jQuery, we need to write our own method to handle this type of situation.

So this is my code

<form>
  input 1: <input value="one"><br>
  input 2: <input value="two"><br>
  select 1:
  <select>
    <option>Bla1</option>
    <option>Bla2</option>
    <option>Bla3</option>
  </select><br>
  Checkbox 1: <input type="checkbox"><br>
  Checkbox 2: <input type="checkbox" checked><br>
  <button action="submit">Save</button>
</form>

and Javascript code would be

const inputs = document.querySelectorAll("input, select");
for (let el of inputs){
  el.oldValue = el.value + el.checked;
}

// Declares function and call it directly
var setEnabled;
(setEnabled = function() {
  var e = true;
  for (let el of inputs) {
    if (el.oldValue !== (el.value + el.checked)) {
      e = false;
      break;
    }
  }
  document.querySelector("button").disabled = e;
})();

document.oninput = setEnabled;
document.onchange = setEnabled;

At first, select all the inputs and selects in the form, and store the original value in an object so we could compare it with the changed value.

When the user inputs or selects a value, the setEnabled method is triggered. This method checks whether the old and new values are same. If not, enables the Submit button. Simple as it is 🙂

Share your thoughts