shivamag00
shivamag00

Reputation: 481

Button onclick event does not redirect to another page although it calls the functions

The following code does not redirect to the given webpage

<form>
    <button onclick='window.location.replace("../magnet/index.php")'>Replace document</button>
</form>

Upvotes: 2

Views: 7514

Answers (3)

Abdallah
Abdallah

Reputation: 89

The answer was to add type="button" like @shivamag00 explained.

But be careful with replace(), it's not possible to use "back" to navigate back to the original document since you are replacing the history state.

An alternative is to use the assign() function, (documentation here)

Suppose you have a base url as

www.website.come

and want to go to

www.website.come/new-page

it's simple

<button type="button" onclick='window.location.assign("new-page")'>Go to new page</button>

It's worked for me, hope it's useful for someone else.

Upvotes: 0

Muhammad Zahid
Muhammad Zahid

Reputation: 11

Even better, you can place your redirect code into a JavaScript function. Then you can call that function from within your HTML code. Like this

<script type="text/javascript">
<!--
function redirectTo(sUrl) {
window.location = sUrl
}
//-->
</script>
<button onclick="redirectTo('../magnet/index.php')">Get HTML!</button>

Hope this will work for you. Cheers

Upvotes: 1

shivamag00
shivamag00

Reputation: 481

It is so because when you create a button within the form tags, it is created as a submit button by default. So, instead of redirecting the webpage, it submits the data and reloads the current webpage.

The following code will do the required job because now, the type of the button is button and not submit.

<button type="button" onclick='window.location.replace("../magnet/index.php")'>Replace document</button>

Upvotes: 1

Related Questions