Steve B
Steve B

Reputation: 37660

Can't cancel a button click

I have a html button in a web page. When I click the button, I'd like to redirect to another page.

I have this code :

<button id="btn" type="submit" style="width: auto">
    <div style="height: 40px">
        <img alt="Button" src="/images/somepicture.png" style="float: left" />
        <span style="margin: auto">Label</span>
    </div>
</button>
<script language="javascript" type="text/javascript">
    $(function () {
        $("#btn")
        .mousedown(function (event) {
            window.location.href = "otherpage";
            event.preventDefault();
        });
    });
</script>

However, this code is not behaving as expected. The page is simply posting, and the redirection does not occurs.

What is wrong with my code?

Upvotes: 1

Views: 772

Answers (2)

Ram
Ram

Reputation: 144689

note that it's not valid to use div tags within button tags, try this:

$(function() {
    $("#btn").click(function(event) { // you can use click handler
        window.location = "http://www.stackoverflow.com";
        event.preventDefault();
    });
});

Upvotes: 2

Josh Mein
Josh Mein

Reputation: 28645

This should work for you:

$(function () {
    $("#btn").click(function (event) {
        event.preventDefault();
        window.location.href = "otherpage";
    });
});

Note: Text and images are the only valid contents for a <button>. I don't think this would be the cause of your issue, but it is best to follow the standards.

Upvotes: 3

Related Questions