Home > Back-end >  how to redirect a html page in javascript
how to redirect a html page in javascript

Time:03-19

I'm working on the Javascript page for my registration form. I simply just can't figure out how to make the page redirect to another page if everything's filled out.

document.getElementById("check").onclick = function() {
  let allAreFilled = true;
  document.getElementById("myForm").querySelectorAll("[required]").forEach(function(i) {
    if (!allAreFilled) return;
    if (!i.value) allAreFilled = false;
    if (i.type === "radio") {
      let radioValueCheck = false;
      document.getElementById("myForm").querySelectorAll(`[name=${i.name}]`).forEach(function(r) {
        if (r.checked) radioValueCheck = true;
      })
      allAreFilled = radioValueCheck;
    }
  })
  if (!allAreFilled) {
    alert('Fill all the fields');
  }
  else {
    window.location.replace("http://www.w3schools.com");
  }
}; 

CodePudding user response:

I'm giving my sample script for the same possible problem I hope this helps

HTML

<pre>
<!DOCTYPE HTML>
<html>
<body>
<p id=P >Fill in all checkboxes</p>
    <form>
        <input type=radio />
        <label>Check 1</label>
        
        <input type=radio />
        <label>Check 2</label>
        
        <input type=radio />
        <label>Check 3</label>
    </form>
</body>
</html>
</pre>

JavaScript

window.onload = () => 
{

var radio = document.querySelectorAll('[type=radio]'),
p = document.getElementById("P");
 
radio.forEach( 
    function(i)
    {
        i.onchange = () => 
        {
            var checked = document.querySelectorAll("[type=radio]:checked"),
                leftover = radio.length - checked.length;
            p.innerHTML = "leftover checkbox "   leftover;
            
            if(radio.length == checked.length)
            {
                alert("All checked");
                window.location.href = "https://ilhamb.com/";
            }
            
        }
    }
)
}

CodePudding user response:

If you are using forms, then you would submit the results. This sends the data to the server.
Have a look at this: https://www.javascripttutorial.net/javascript-dom/javascript-form/

CodePudding user response:

This code

window.location = "w3schools.com"

Or

window.location.href = "w3schools.com"

should do it

CodePudding user response:

Use window.location.href to redirect within the same tab /window or use window.open() to redirect in a new tab /window.

As Quentin pointed out, you are already using an appropriate way to redirect. May I suggest opening the console and checking if there are console errors ? Also make sure that your program actually reaches the redirect by using a browser breakpoint or console logs.

  • Related