Reputation: 327
I've searched the questions here about 'how to enable my disabled button' but the one with the 'removeAttribute' simply does not work, don't know why. I have this problem - once I reach 0 with my decrementing button it goes disabled so the user can't decrement to negative number but the problem is when I use the increment button the decrement one stays disabled, why ? I will be very greatfull if you guys tell me another way to solve this task. The point is I am now allowed to decrement below 0. Here are my HTML and JS:
var value = 1;
var plus = document.getElementById('plus');
var minus = document.getElementById('minus');
function add() {
value++;
document.getElementById('num').innerHTML = value;
}
function take() {
value--;
document.getElementById('num').innerHTML = value;
if (value == 0) {
minus.disabled = true;
} else {
minus.disabled = false;
}
}
<input type="button" value="ADD" id="plus" onclick="add();">
<input type="button" value="TAKE" id="minus" onclick="take();">
<span id="num">1</span>
Upvotes: 0
Views: 92
Reputation: 207501
Because you do not run the logic when you click on the add button. You only do it on the minus button.
I would break it out into it own function
var value = 1;
var plus = document.getElementById('plus');
var minus = document.getElementById('minus');
function add() {
value++;
document.getElementById('num').innerHTML = value;
setBtnStates();
}
function take() {
value--;
document.getElementById('num').innerHTML = value;
setBtnStates();
}
function setBtnStates() {
if (value == 0) {
minus.disabled = true;
} else {
minus.disabled = false;
}
}
<input type="button" value="ADD" id="plus" onclick="add();">
<input type="button" value="TAKE" id="minus" onclick="take();">
<span id="num">1</span>
The statement can be simplified to
function setBtnStates() {
minus.disabled = value == 0;
}
Upvotes: 3