Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html button and href not working as expected

In the below code I have an href and a button that uses javascript to post to a new page. The href works when I click it but the button that uses javascript takes several clicks and works intermittently. Some times only three clicks but can be as high as 19 clicks depending on how hard I click the mouse :)

Any ideas why these are behaving differently?

<head>
    <script type="text/javascript">
        function myFunction() {
            window.location.href = 'tournaments.aspx';
        }
    </script>
</head>
<body>
<form>
<div style="width:400px; height: 600px; border: 1px solid black;" align="center" >
    <div>
        <input type="image" name="ctl02" src="Images/Advertisement.png" />
    </div>
    <div>
        <input type="image" name="ctl03" src="Images/ISETLogo.png" />
    </div>
    <div >
        <button onclick="myFunction()">Click me</button>
        <a href="tournaments.aspx">tournaments</a>
    </div>
</div>
</form>

like image 376
joncodo Avatar asked Feb 24 '26 01:02

joncodo


1 Answers

It's probably because you have a single button in a <form> tag, which will by default try and submit the form when clicked. So in addition to trying to load 'tournaments.aspx' in the current window, you're also POSTing to the current page which will react by reloading.

To prevent this default behaviour, add return false; within your onclick:

<head>
    <script type="text/javascript">
        function myFunction() {
            window.location.href = 'tournaments.aspx';           
        }
    </script>
</head>
<body>
<form>
<div style="width:400px; height: 600px; border: 1px solid black;" align="center" >
    <div>
        <input type="image" name="ctl02" src="Images/Advertisement.png" />
    </div>
    <div>
        <input type="image" name="ctl03" src="Images/ISETLogo.png" />
    </div>
    <div >
        <button onclick="myFunction(); return false;">Click me</button>
        <a href="tournaments.aspx">tournaments</a>
    </div>
</div>
</form>
</body>
like image 169
Widor Avatar answered Feb 25 '26 15:02

Widor