2

I have a webpage - http://www.example.com/ - where I have a button. On click of the button I need to go to a particular link (www.google.com). The button is like :

<input type="button"
       onclick="javascript:location.href='www.google.com'"
       value="Click" />

But this button opens a page "http://www.example.com/www.google.com" which is wrong URL.

I have tried window.location, document.location, document.location.href, location.href but all in vain.

The URL in my onclick can not be restricted to begin with 'http://'.

CharlesB
  • 86,532
  • 28
  • 194
  • 218
Riju Mahna
  • 6,718
  • 12
  • 52
  • 91

3 Answers3

8

You can use the "current" protocol by prefixing your URLs with //

slugonamission
  • 9,562
  • 1
  • 34
  • 41
4

prefixing http:// before url may solve your issue.

if (!url.match(/^http?:\/\//i) || !url.match(/^https?:\/\//i)) {
        url = 'http://' + url;
    }

check this and this for more information.

Satish
  • 696
  • 1
  • 11
  • 22
2

Since you did not include a protocol (such as for example http), your browser will interpret www.google.com as a link to http://www.example.com/www.google.com, since you are currently on http://www.example.com. Add whatever protocol you want to the href-string, but if you are referring to somewhere else than on the site itself, you must have the protocol.

Fluffeh
  • 33,228
  • 16
  • 67
  • 80
Findus
  • 130
  • 9