This code below for some reason doesn't work when trying to redirect. I have tried several other ways such as window.location.href and more. The only thing that works is window.open ("")
but this opens a page in a new window when I need it to be on the same. If I do window.open("", "_self")
then it does not work again. If I replace the window.location
with an alert
it works fine, so I think the overall code is normal just something preventing it from redirecting on the same page. This issue is also on my Windows Chrome and a Mac Firefox.
<html>
<head>
<script type="text/javascript">
function checkAnswers(){
getElementById("myQuiz");
if(myQuiz.elements[1].checked){
window.location = "www.google.com";
}else{
alert("Failed");
}
};
</script>
</head>
<body>
<img src="Castle.JPG" />
<form id="myQuiz" onsubmit="checkAnswers()" action="">
<p>Name the country this castle is located in?
<br/>
<input type="radio" name="radiobutton" value="A"/>
<label>England</label>
<input type="radio" name="radiobutton" value="B"/>
<label>Ireland</label>
<input type="radio" name="radiobutton" value="C"/>
<label>Spain</label>
<input type="radio" name="radiobutton" value="D"/>
<label>France</label>
<input type="submit" name="submit" value="Submit"/>
<input type="reset" name="reset" value="Reset"/>
</p>
</form>
</body>
</html>
The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
window. location is an object that holds all the information about the current document location (host, href, port, protocol etc.). location. href is shorthand for window.
The window. location is read/write on all compliant browsers. The document. location is read-only in Internet Explorer but read/write in Firefox, SeaMonkey that are Gecko-based browsers.
When you change the location, you must give it an absolute URL:
location.href = '/some_page_on_my_site';
Or:
location.href = 'http://www.google.com';
Or:
location.href = '//www.google.com';
The last one will go to http or https, depending the current scheme. Thanks @Derek
2018
multibrowser: safari, chrome, firefox:
just this work:
window.location.replace(url)
another options that tries assign url to window.location or window.location fails
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With