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>
A quick way to have that functionality is to listen for the submit
event on your form
that checks if both the input
s 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 theinput
s 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 input
s, 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).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.