Reputation: 1472
I'm trying to keep track of the number of items a user has clicked on by removing one from the counter span using a basic JS function. I have to keep track of anywhere between 5 to 10 items so each time the button is clicked I am removing one from the div span that keeps count. It's working but I do not want it going to negative values. How do I keep the button from removing 1 after it has been used once? Basically, I want the function to only fire once for each button.
Here is the codepen as it is now: CODEPEN
Here is what I have right now:
var currentValue = 9;
var add = function(valueToAdd){
currentValue += valueToAdd;
document.getElementById('number').innerHTML = currentValue;
if (this.currentValue == 0) {
alert("YOU ARE AT 0 ");
currentValue - 0
}
if (!isNaN(currentValue) && currentValue > 0) {
// Decrement one
currentValue - 1;
} else {
return false;
}
};
HTML:
<div id="text">Number of items:<span id="number">9</span><div>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
<button onclick="javascript:add(-1)">remove only 1</button>
Upvotes: 0
Views: 438
Reputation: 19294
You have great interest in inserting the buttons programmatically, you'll have a much greater flexibility. And you can hook the function to a function that you bind to have the right this
.
Below is the code for buttons that handle a 'quantity' property, and disable themselves when quantity reaches 0.
http://codepen.io/anon/pen/gJtry
<div id="text">Number of items:<span id="number">9</span>
<div id="oneTimeButtons">
</div>
<div id='youDidIt' hidden>!!! You did it !!!</div>
code :
var buttonCount = 9;
var quantityPerButton = 1; // try 2 or more
var totalValue = 0;
var gID=document.getElementById.bind(document);
var elem = gID('oneTimeButtons');
for (var i=0; i<buttonCount; i++) {
var bt = document.createElement('button');
bt.id='qttBt'+i;
bt.onclick = add.bind(bt, -1);
bt.quantity=quantityPerButton;
totalValue+=bt.quantity;
bt.buildTitle = function( i) {
this.innerHTML='Qtty button '+i+' ('+this.quantity+')';
}.bind(bt, i);
bt.buildTitle();
elem.appendChild(bt);
}
gID('number').innerHTML=totalValue;
function add (valueToAdd) {
this.quantity+=valueToAdd;
this.buildTitle();
if (this.quantity ==0) this.disabled=true;
totalValue += valueToAdd;
gID('number').innerHTML = totalValue;
if (totalValue == 0) {
console.log("YOU ARE AT 0 ");
gID('youDidIt').hidden=false;
}
};
Upvotes: 1