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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With