JS按照条件,禁用按钮 要求都是 6~16 位
时间: 2024-05-11 13:14:10 浏览: 21
以下是JS实现禁用按钮的代码:
```javascript
// 获取按钮元素
const btn = document.getElementById('myButton');
// 获取输入框元素
const input = document.getElementById('myInput');
// 给输入框绑定输入事件
input.addEventListener('input', function() {
// 获取输入框的值
const value = input.value.trim();
// 判断输入框的值是否符合条件
if (value.length < 6 || value.length > 16) {
// 如果不符合条件,则禁用按钮
btn.disabled = true;
} else {
// 如果符合条件,则启用按钮
btn.disabled = false;
}
});
```
这段代码中,我们通过`document.getElementById`方法获取了按钮和输入框元素,并给输入框绑定了一个`input`事件。在事件处理函数中,我们先获取输入框的值,并使用`trim`方法去除首尾空格。然后,我们判断输入框的值是否符合条件,如果不符合条件,则禁用按钮;如果符合条件,则启用按钮。最后,我们通过`disabled`属性来控制按钮的禁用状态。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)