Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to redirect to another page when a certain condition is true using javascript

I need to redirect to another page based on the number of certain moves. For example: if the number of moves after you find all the pairs are between 4 - 8, you will be redirected to page 1 to see your result, 10 - 16 is on page 2 and so on, but my code still goes to page 1.

 function validate() {
  var clickHere = document.getElementById("terms");
  if(clickHere.checked){
    if(counterVal >= 4 || counterVal <=8){
      location.replace("https://www.w3schools.com/js/")
    }
    else{
      location.replace("https://javascript.info/")
    }
  }else{
    alertify.error('Click the checkbox first.')
  }
like image 911
Vasco Wayne Avatar asked Oct 25 '25 04:10

Vasco Wayne


2 Answers

if the number of moves after you find all the pairs are between 4 - 8, you will be redirected to page 1 to see your result, 10 - 16 is on page 2 and so on, but my code still goes to page 1

If countVal is 4 to 8, you want link https://www.w3schools.com/js/.

But in the code, that case condition has counterVal >= 4 ||. The condition will be true if the countVal is more then 8; that is the problem.

if(counterVal >= 4 || counterVal <=8){

Rewrite it like

if(counterVal >= 4 && counterVal <=8){
like image 78
Plutus Avatar answered Oct 26 '25 18:10

Plutus


The simplest way to use JavaScript to redirect to a URL is to set the location property to a new URL using window.location.href. The JavaScript code looks like this: window.location.href = ‘https://ExampleURL.com/’; it is a property that tells you what URL is currently being viewed. Setting a new value, you are telling the browser to load that new URL, similar to what would happen if a user clicked a link. You function should look like this:

function validate() {
  var clickHere = document.getElementById("terms");
  if(clickHere.checked){
    if(counterVal >= 4 || counterVal <=8){
      window.location.href = "https://www.w3schools.com/js/"
    }
    else{
      window.location.href ="https://javascript.info/"
    }
  }else{
    
    alertify.error('Click the checkbox first.')
  }
like image 37
matthew Avatar answered Oct 26 '25 17:10

matthew