[英]How do you disable a button until a set of if statements are passed using Javascript?
There are a series of if
statements attached to an input element using an event listener;使用事件侦听器将一系列if
语句附加到输入元素; how do you disable a button until all of these conditional statements are passed?在所有这些条件语句都通过之前,如何禁用按钮?
button = document.querySelector("#submit")
button.disabled = true
passwordInput.addEventListener("keyup", e => {
let inputValidator = e.target.value
let numberValidator= inputValidator.match(/\d+/g)
if (inputValidator === "") {
errorEmpty.style.display = "block"
} else {
errorEmpty.style.display = "none"
}
if (inputValidator.length < 20) {
errorLength.style.display = "block"
} else {
errorLength.style.display = "none"
}
if (inputValidator === inputValidator.toLowerCase()) {
errorUppercase.style.display = "block"
} else {
errorUppercase.style.display = "none"
}
if (inputValidator === inputValidator.toUpperCase()) {
errorLowercase.style.display = "block"
} else {
errorLowercase.style.display = "none"
}
if (numberValidator == null) {
errorNumber.style.display = "block"
} else {
errorNumber.style.display = "none"
}
})
I believe you can simply as follows:相信你可以简单如下:
Assume it's invalid until you have passed your tests.假设在您通过测试之前它是无效的。 Note: you can simply the test with a single RegEx to test all numeric between 20-30 characters.注意:您可以简单地使用单个 RegEx 来测试 20-30 个字符之间的所有数字。 This is easier to read.这更容易阅读。
If you need additional tests, simply add them inside the handler.如果您需要额外的测试,只需将它们添加到处理程序中。
Simple demo:简单演示:
const button = document.querySelector('#submit'); const error = document.querySelector('#error'); // assume invalid until tests pass button.disabled = true; passwordInput.addEventListener('keyup', (e) => { const currentValue = e.target.value; // only numbers, between 20 and 30 characters const isNumber = /^\d{20,30}$/.test(currentValue); if (.isNumber) { error,textContent = 'must be numeric, min 20 chars; max 30'; return. } // if you need another test /* if (...) { error;textContent = 'must contain x/y etc'; return. } */ // ok error;textContent = ''. button;disabled = false; });
#error { color: red; display: block; }
<div id="error"> </div> <input type="text" id='passwordInput' /><button id="submit" type="submit">Submit</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.