【问题标题】:How to disable the button(should not do anything) if either of input is empty?如果任一输入为空,如何禁用按钮(不应执行任何操作)?
【发布时间】:2021-11-15 04:42:16
【问题描述】:

enter image description here 没有号码就显示Nan,怎么禁用呢?

【问题讨论】:

  • 请将代码和数据添加为文本 (using code formatting),而不是图像。图片:A)不允许我们复制粘贴代码/错误/数据进行测试; B) 不允许根据代码/错误/数据内容进行搜索;和many more reasons。除了代码格式的文本之外,只有在图像添加了一些重要的东西,而不仅仅是文本代码/错误/数据传达的内容时,才应该使用图像。
  • 在设置res.value之前尝试使用if语句检查num1num2是否不为空

标签: javascript html button


【解决方案1】:

通过添加禁用属性来禁用 html 中的按钮。为仅在有值时才启用按钮的输入编写一个 on-change 处理程序。

参考:https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event

const input1 = document.querySelector('#num1');
const input2 = document.querySelector('#num2');

input1.addEventListener('change', handleButton);
input2.addEventListener('change', handleButton);

function handleButton() {
  if(input1.value && input2.value) {
    document.querySelector(".button").removeAttribute("disabled");
  } else {
    document.querySelector(".button").setAttribute("disabled", "disabled");
  }
}

您可以通过您使用的类名来定位按钮。我在答案中使用了 .button。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-06
    • 1970-01-01
    • 2018-09-03
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多