Reputation: 13
I am trying to create a quantity selector like what you would find in a grocery store website or in most e-commerce sites. (One with +1 and -1 buttons) I can make the first selector work but can't seem to get the second one to.
Here's the code and HTML I have so far:
function addNum1() {
var newValue = Number(ordernow.firstvalue.value);
newValue +=1;
ordernow.firstvalue.value = newValue;
}
function minusNum1() {
var subNum = Number(ordernow.firstvalue.value);
if (subNum > 0) {
subNum -= 1;
ordernow.firstvalue.value = subNum;
}
}
function addNum2() {
var newValue = Number(ordernow.firstvalue2.value);
newValue2 +=1;
ordernow.firstvalue2.value = newValue2;
}
function minusNum2() {
var subNum2 = Number(ordernow.firstvalue2.value);
if (subNum2 > 0) {
subNum2 -= 1;
ordernow.firstvalue2.value = subNum2;
}
};
<body>
<div class=container>
<form name="orderup" id="ordernow">
<p> Chicken     $4.57</p>
Quantity<input type="button" id="firstminus" value="- 1" onclick="minusNum1()"/>
<input type="text" id="firstvalue" value="0"/>
<input type="button" id="firstadd" value="+1" onclick="addNum1()"/>
<p> Beef     $3.32</p>
Quantity<input type="button" id="firstminus2" value="- 1" onclick="minusNum2()"/>
<input type="text" id="firstvalue2" value="0"/>
<input type="button" id="firstadd2" value="+1" onclick="addNum2()"/>
</form>
</div>
</body>
Upvotes: 0
Views: 141
Reputation: 14810
If you open your browser's development tools the console should show an error message. On Chrome I get:
Uncaught ReferenceError: newValue2 is not defined
This is because addNum2()
declares newValue but then uses newValue2 on the next line.
function addNum2() {
var newValue = Number(ordernow.firstvalue2.value);
newValue2 +=1;
ordernow.firstvalue2.value = newValue2;
}
var newValue = Number(ordernow.firstvalue2.value);
newValue2 +=1;
You can use the same var name because you are in a different function scope.
Fix:
function addNum2() {
var newValue = Number(ordernow.firstvalue2.value);
newValue +=1;
ordernow.firstvalue2.value = newValue;
}
Always check for error messages in the console and run your javascript in the debugger when something is "mysteriously" not working.
Upvotes: 1