user2471356
user2471356

Reputation: 1

javascript 'go to page' form script

I need to setup a form on my site which will enable people to quickly navigate to a page by typing a number into a form and clicking 'go'.

I've got the following code which works in part:

<script type="text/javascript">
function goTo()
{
window.location = document.forms[0].where.value ;
return false;
}
</script>
</head>

<body>
<form action="" method="post" onsubmit="return goTo()">
<input type="text" name="where" value="Enter page number" onfocus="if(this.value ==     this.defaultValue) this.value = '';" onblur="if(this.value == '') this.value = this.defaultValue;">
<input type="submit" value="Go">
</form>
</body>
</html>

I'm injecting this code onto a page with a url, for example, like:

www.examplesite.com/navigate

The form appears just fine on the /navigate page. Now I'd like my users to be able to type a number into the form which corresponds to a url on my site. For example to get to:

www.examplesite.com/1234

the user would type '1234' into the form and press 'Go'.

What's happening instead however is the page the script is trying to open is:

www.examplesite.com/navigate/1234

Does anyone have any idea how I could modify the script to ensure it always opens a page at the root of the site rather than a subdirectory?

Thanks in advance for any help. Appreciate it.

Upvotes: 0

Views: 3414

Answers (1)

Ivan Chernykh
Ivan Chernykh

Reputation: 42186

Try this:

window.location = "/" + document.forms[0].where.value ;

/ means root. Without it the path is relative to current folder.
In some cases you can use base tag, have a look: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/base

Upvotes: 8

Related Questions