sd_dracula
sd_dracula

Reputation: 3896

JavaScript window.location is not working

I don't seem to be able to get the JS window.location to work in my asp.net website.

    <head runat="server">
    <title></title>
    <script type="text/javascript">
        function Redirect(URL) {
            window.location.href = URL;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <button id="test" title="test" onclick="Redirect('http://www.google.com');">click me</button>
    </div>
    </form>
</body>
</html>

The button seems to do a postback instead. Is my syntax wrong? I have tried window.location without href and same result.

Upvotes: 1

Views: 1336

Answers (3)

Satish Kumar sonker
Satish Kumar sonker

Reputation: 1288

Please return false from onclick event to prevent page from postback

<button id="test" title="test" onclick="Redirect('http://www.google.com'); return false;">click me</button>

Upvotes: 0

Nitin Garg
Nitin Garg

Reputation: 896

Try changing your javascript code with below code

function Redirect(URL) {
    window.location.href = URL;
    return false;
}

And add return when you call your javascript function i.e.

<button id="test" title="test" onclick="return Redirect('http://www.google.com');">click me</button>

In your code it was getting PostBack when you didn't return false.

Just to add if you add

<asp:Button ID="Button1" runat="server" OnClientClick="return Redirect('http://www.google.com');" onclick="Button1_Click" Text="Button" />

Hope this helps you.

Upvotes: 0

Adil Naik
Adil Naik

Reputation: 30

I think you should try html input

<input type="button" value="click me" id="test" onclick="Redirect('http://www.google.com');" />

Upvotes: 1

Related Questions