button plus and minus script |
button plus and minus script |
Louffeman |
Oct 10 2016, 12:15 PM
Post
#1
|
Member Group: Members Posts: 69 Joined: 21-June 14 Member No.: 21,123 |
Hi,
I want to create à script for a plus and minus button, I meet some difficulties, the initial value is 0, when I click +, it increases immediately to 2, than, 2,3,4.....normally. but it can't increase to 1, than 2,3,4... and when I click -, it decreases until to 1, not possible to 0. I wish someone can help, and thanks a lot ! it is my script: <div id="input_div"> <input type="button" value="-" id="moins" onclick="minus()"> <input type="text" size="8" value="0" id="count"> <input type="button" value="+" id="plus" onclick="plus()"> </div> <script src="js/jquery.js"></script> <script> var count = 1; var countEl = document.getElementById("count"); function plus(){ count++; countEl.value = count; } function minus(){ if (count > 1) { count--; countEl.value = count; } } </script> |
CharlesEF |
Oct 10 2016, 12:49 PM
Post
#2
|
Programming Fanatic Group: Members Posts: 1,981 Joined: 27-April 13 From: Edinburg, Texas Member No.: 19,088 |
What you describe is exactly what you have coded to happen. You should rewrite your plus() and minus() functions. I will show you how to do 1 and I will leave the other to you.
HTML CODE <input type="button" value="+" id="plus" onclick="plus(parseInt(document.getElementById("count").value))"> Javascript CODE function plus(count){ You don't need the line 'var count = 1;' and I didn't use document.getElementById("count").value = count++; } 'var countEl = document.getElementById("count");' but you can put it in my code if you want to. If you need help with the minus() function just post back with your new code. |
CharlesEF |
Oct 10 2016, 02:17 PM
Post
#3
|
Programming Fanatic Group: Members Posts: 1,981 Joined: 27-April 13 From: Edinburg, Texas Member No.: 19,088 |
Now that I have a little more time let me explain. The code I posted is how I would do it but you don't have to. If you want to use your code instead then you need to fix it.
The reason your plus() starts at 2 is this 'var count = 1;'. To start from 1 you need to change it to 'var count = 0;'. The reason your minus() never gets to 0 is this 'if (count > 1) {'. To get to 0 it should be 'if (count > 0) {'. |
Louffeman |
Oct 11 2016, 01:41 AM
Post
#4
|
Member Group: Members Posts: 69 Joined: 21-June 14 Member No.: 21,123 |
thank you so much, it's solved
|
Lo-Fi Version | Time is now: 27th April 2024 - 09:49 PM |