Sid Brown
Sid Brown

Reputation: 111

How to reload a page in javascript while limiting the count of number of times a button is clicked?

What I aiming for is - to reload a page every time the reload button is clicked (using javascript function : window.location.reload ();) and also keep track of number of times the button (Retake Test) is clicked. The page should reload only for the first three clicks. If the button is clicked more than three times, it should lead to a different page

Code:

   <div class = "text-center"> <button type="button" class="btn btn-success 
    btn-block" onclick ="myCheck();">Retake Test</button> 

and here is the solution I came of with (which obviously did not work)

<script>
var count = 0;
 function myCheck () {
count = count+1;
 if (count < 3) {
    window.location.reload();
    }
else {
    document.write ("YYY");
    }
 }
 </script>

Upvotes: 0

Views: 971

Answers (4)

Osama
Osama

Reputation: 3030

Use localStorage.setItem and localStorage.getItem

 <script>
 var count=typeof localastrorage.getItem('count')!="null"? localstorage.getItem('count'):0;
function myCheck () {
   localStorage.setItem("count",count);
count = count+1;
 if (count < 3) {
    window.location.reload();
    }
else {
    document.write ("YYY");
    }
 }
 </script>

Upvotes: 0

Ahmad
Ahmad

Reputation: 1931

Your counts are getting lost on page reload. Use localstorage or cookies

"use strict";

function myCheck() {
  var count = localStorage.getItem('count') || 0;
  if (count < 3) {
    localStorage.setItem('count', (count += 1) )
    return window.location.reload();
  }
  // more than or equal to 3 times
  document.write("YYY");
}

Upvotes: 0

Alexander Solonik
Alexander Solonik

Reputation: 10250

You can try localStorage.

<script>
 localStorage.setItem('count', '0');
 function myCheck () {
  localStorage.setItem('count',  +(localStorage.getItem('count'))+ 1)
    if (+(localStorage.getItem('count')) < 3) {
      window.location.reload();
    }
    else {
      document.write ("YYY");
    }
 }
 </script>

This is a hurried attempt , you can make your code more succinct ofcourse !

ADDITIONAL NOTE: Also avoid using inline javascript like onclick ="myCheck();" use addEventListener instead.

Upvotes: 1

Stephan
Stephan

Reputation: 2115

Since your variables get reset by reloading the page, you maybe want to save count somewhere else. Cookies would be a useful option, in modern browser one could also use local storage.

However maybe the solution you are looking for is reloading only a part of your webpage via AJAX?

Upvotes: 0

Related Questions