Home > Mobile >  How to disable html form submit button if the input values are the same
How to disable html form submit button if the input values are the same

Time:09-29

Please I want a simple form validator that disable html input form in the values are the same in js.

<input type="text" value="john">
<input type="text" value="john">
<button>Test</button>

CodePudding user response:

A quick way to have that functionality is to listen for the submit event on your form that checks if both the inputs have the same value.

Here's a live demo:

/** select the form and both the inputs, select them once and use them as many as needed */
const myForm = document.getElementById('my-form'),
  inp1 = document.getElementById('inp-1'),
  inp2 = document.getElementById('inp-2');

/** 
* listen for "submit" events on the form 
* if the trimmed values of both the inputs is the same then we prevent the form from being submitted
*/
myForm.addEventListener('submit', e => inp1.value.trim() === inp2.value.trim() && e.preventDefault());
<!-- your form should have an ID to make it easier for us to select it on the JS part -->
<!-- your form should also have an "action" attribute along with the appropriate "method" attribute -->
<form id="my-form">
  <!-- give each input an ID to make it easier for us to select it on the JS part -->
  <input id="inp-1" type="text" value="john">
  <input id="inp-2" type="text" value="john">
  <!-- the button should be of type "submit" to allow submit events to be catched -->
  <button type="submit">Test</button>
</form>

In the above example the String.prototype.trim() method was used to remove whitespace from both ends of the inputs values.

The canceling of the form submission is done by calling preventDefault() method on the submit event object that is passed to the listener function (I called it e, we usually call it e by the way) when both the values of the inputs, when trimmed, is the same.

The line inp1.value.trim() === inp2.value.trim() && e.preventDefault()) will call preventDefault method only if both the trimmed values of the input is the same (as we're using the && (AND) operator) and will allow the form to be submitted otherwise (when the fields have different values).

  • Related