仅当文本输入为0时禁用按钮

时间:2018-10-03 18:28:02

标签: javascript html css

我有以下代码:

var total = document.getElementById('total--input');

document.getElementById('btn-increment-total').addEventListener('click', function() {
  if (total.value > 1) {
    console.log('enabled');
    document.getElementById('btn-decrement-total').enabled = true;
  }

  total.value++;
});

document.getElementById('btn-decrement-total').addEventListener('click', function() {
  if (total.value == 0) {
    console.log('disabled');
    document.getElementById('btn-decrement-total').disabled = true;
  }

  total.value--;
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">

“减量”按钮似乎可以工作,并且在满足条件时会自动禁用。

但是“增加”按钮似乎并没有重新启用“减少”按钮。有谁知道为什么以及如何解决这个问题?

5 个答案:

答案 0 :(得分:1)

没有enabled属性,您应该使用disable="false"

document.getElementById('btn-decrement-total').disabled = false;

代替:

document.getElementById('btn-decrement-total').enabled = true;
_______________________________________________^^^^^^^

工作示例:

var total = document.getElementById('total--input');

document.getElementById('btn-increment-total').addEventListener('click', function() {
  total.value++;

  if (total.value > 0) {
    console.log('enabled');
    document.getElementById('btn-decrement-total').disabled = false;
  }

});

document.getElementById('btn-decrement-total').addEventListener('click', function() {
  total.value--;

  if (total.value == 0) {
    console.log('disabled');
    document.getElementById('btn-decrement-total').disabled = true;
  }
});
<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">

答案 1 :(得分:0)

enabled不是有效的属性,请改用disabled = false

答案 2 :(得分:0)

您需要以var / let或const分配输入。

尝试这种方式:

const total = document.querySelector("#total--input");

答案 3 :(得分:0)

我必须添加return语句并更改一些代码行,但这应该可以工作。

 const disableBtn = function (id, mode) {
      document.getElementById(id).disabled = mode;
    };


document.getElementById('btn-increment-total').addEventListener('click', function () {
  let total = document.getElementById('total--input');

  if (total.value >= 0) {
    disableBtn('btn-decrement-total', false);

  }
  total.value++;

});

document.getElementById('btn-decrement-total').addEventListener('click', function () {
  var total = document.getElementById('total--input');
  total.value--;
  if (total.value <= 0) {
    disableBtn('btn-decrement-total', true);
    return
  }

});



<button id="btn-increment-total">plus</button>
<button id="btn-decrement-total">min</button>
<input type="text" id="total--input" value="1">

答案 4 :(得分:0)

在比较值之前尝试将输入元素中的值解析为整数...

var n1 = Number(document.getElementById('input_element').value).

然后您可以检查其是否满足条件