lhan
lhan

Reputation: 4635

HTML Input type image won't redirect upon click?

I have the following code, which works fine:

<input type="button" name="btnHello" value="Hello" onclick="Test();"/>

and here is the JS function:

function Test() {
  window.location.href = "Page2.aspx";
}

When I click my Hello button, it redirects to Page2.aspx like expected. But when I change my button to an image button:

<input type="image" src="images/myimage.jpg" name="btnHello" onclick="Test();"/>

It no longer works. The page posts back, but its more like a refresh. I can put an alert in the JS function to see that it is getting called, but I'm not sure why the redirect doesn't work? Has anyone ever experienced this?

I know its probably something stupid, but I'm stumped.

Many thanks in advance!

Upvotes: 2

Views: 8202

Answers (4)

Alexander Brill
Alexander Brill

Reputation: 96

input type image does not have a onclick event. You need to use the img tag instead. <img onclick="Test();">

Upvotes: -1

Richard Banks
Richard Banks

Reputation: 2983

The redirect is getting cancelled because you are doing a postback. Add return false; after the function test();

e.g

onclick="test();return false;"

Upvotes: 2

Naftali
Naftali

Reputation: 146310

Try using an img tag:

<img src="images/myimage.jpg" name="btnHello" onclick="Test();"/>

Upvotes: 1

SLaks
SLaks

Reputation: 887469

You need to return false from the event handler to prevent the default action.

However, since you don't want it to postback in the first place, you might as well use an ordinary <img /> instead of an <input />.

Upvotes: 6

Related Questions