Nick Audenaerde
Nick Audenaerde

Reputation: 1025

javascript counter with if else

I'm trying to make a counter, that can only go from 0, to a max of 10, right now I can add and delete number from the counter, but for some reason my if/else never works, no matter where I put them. I'm a real noob to javascript so if anyone could give me some advice it would be highly appreciated.

Here's my code:

 <script type="text/javascript">
var clicks = 0;
if (clicks < 0) {
    clicks = 0;
    document.getElementById("ticketAmmount").innerHTML = clicks;
}
function onClick() {
    clicks += 1;
    document.getElementById("ticketAmmount").innerHTML = clicks;
};
function offClick() {
    clicks -= 1;
    document.getElementById("ticketAmmount").innerHTML = clicks;
}

i also have tried this: but then the counter gives me NaN

<script type="text/javascript">
var clicks = 0;

function onClick() {
if (clicks < 0) {
    clicks = 0;
    document.getElementById("ticketAmmount").innerHTML = clicks;
} else {
 clicks += 1;
    document.getElementById("ticketAmmount").innerHTML = clicks;
}

};
function offClick() {
    clicks -= 1;
    document.getElementById("ticketAmmount").innerHTML = clicks;
}
</script>

Upvotes: 0

Views: 5531

Answers (3)

blex
blex

Reputation: 25634

It's not very complicated:

var minVal = 0, maxVal = 10, clicks = 0,
    display = document.getElementById("ticketAmmount");

function countUp(){
  clicks = Math.min( maxVal, clicks+1 );
  display.innerHTML = clicks;
}

function countDown(){
  clicks = Math.max( minVal, clicks-1 );
  display.innerHTML = clicks;
}
<button onclick="countDown();">-</button>
<span id="ticketAmmount">0</span>
<button onclick="countUp();">+</button>

Upvotes: 2

Rubik
Rubik

Reputation: 1471

You were almost right, put your if within your onClick and offClick functions, and remove the first one (that doesn't seem useful):

var clicks = 0;

document.getElementById("ticketAmmount").innerHTML = clicks;

function onClick() {
    clicks += 1;
    if (clicks > 10) {
        clicks = 10;
    }
    document.getElementById("ticketAmmount").innerHTML = clicks;
};
function offClick() {
    clicks -= 1;
    if (clicks < 0) {
        clicks = 0;
    }
    document.getElementById("ticketAmmount").innerHTML = clicks;
}

Upvotes: 2

Tom
Tom

Reputation: 7740

if (clicks < 0) is being called only once, when the page loads, and right after you set clicks = 0, so it never meets the criteria. You need to put that logic in both the onClick and offClick or extract it out in to some method, for example:

var clicks = 0;
function resetClicks() {
    if (clicks < 0) {
      clicks = 0;
      document.getElementById("ticketAmmount").innerHTML = clicks;
    }
}

function onClick() {
    clicks += 1;
    document.getElementById("ticketAmmount").innerHTML = clicks;
    resetClicks();
};
function offClick() {
    clicks -= 1;
    document.getElementById("ticketAmmount").innerHTML = clicks;
    resetClicks();
}

Upvotes: 1

Related Questions