[英]How to disable html form submit button if the input values are the same
请我想要一个简单的表单验证器,它禁用 html 输入表单,值在 js 中是相同的。
<input type="text" value="john">
<input type="text" value="john">
<button>Test</button>
拥有该功能的一种快速方法是侦听form
上的submit
事件,该事件检查两个input
是否具有相同的值。
这是一个现场演示:
/** 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>
在上面的示例中,
String.prototype.trim()
方法用于从input
值的两端删除空格。
表单提交的取消是通过在传递给监听器 function 的提交事件 object上调用preventDefault()
方法来完成的(我叫它e
,我们通常顺便叫它e
)当input
s 的两个值时,修剪时,是一样的。
仅当输入的两个preventDefault
值&& (AND)
同时(因为我们使用inp1.value.trim() === inp2.value.trim() && e.preventDefault())
&& (AND)
运算符)并将允许以其他方式提交表单(当字段具有不同的值时)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.