SupEldrix
SupEldrix

Reputation: 113

incrementing a number till maximum

So basically I'm trying to add a page counter to my HTML

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div class="content">
        <h1>My Text</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.[...] </p>
    </div>
    <div class="footer">
        <button class="nextP" onclick="nextPage()">Next</button>
        <p>Pages: <a id="pageNum">1/5</a></p>
    </div>
<script src="script/nextPage.js">
</script>
</body>
</html>

The problem is that the number instantly updates to 5 instead of incrementing by +1 .

var pages = 1;

   function nextPage (){
   for (pages; pages < 5; pages++);
   var x = document.getElementById("pageNum").innerHTML = pages + "/5";

}

Upvotes: 0

Views: 342

Answers (3)

ruchika jain
ruchika jain

Reputation: 160

Hope it will work for you.

   <script>
        var pages = 1;
       function nextP (){
           if(pages==5){
            pages=5;
            var x = document.getElementById ("pageNum").innerHTML = pages + "/5";
           }
           else{
            pages=pages+1;
            var x = document.getElementById ("pageNum").innerHTML = pages + "/5";
           }

      }
    </script>

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68393

Due to semicolon ; just after for-loop statement, your for-loop doesn't have a block, remove that semicolon and it should work

 for (pages; pages<5; pages++)
   var x = document.getElementById ("pageNum").innerHTML = pages + "/5";

Use {} for better readability and prevent issues like this

 for (pages; pages<5; pages++)
 {
     var x = document.getElementById ("pageNum").innerHTML = pages + "/5";
 }

Edit

If you want to increment one by one, then no need of for-loop, just a ternary expression would suffice

(pages < 5 ? ++page : 1)

function would become

function nextP(){
    var x = document.getElementById("pageNum").innerHTML = (pages < 5 ? ++page : 1)  + "/5";
}

Upvotes: 1

ruchika jain
ruchika jain

Reputation: 160

Use this script code your nextpage button works absolutely fine.

<script>
    var pages = 1;
    function nextP (){
        pages=pages+1;
        var x = document.getElementById ("pageNum").innerHTML = pages + "/5";
        if(pages==5){pages=0;}
}
</script>

Upvotes: 0

Related Questions