The following doesn't work... (at least not in Firefox: document.getElementById('linkid').click()
is not a function)
<script type="text/javascript"> function doOnClick() { document.getElementById('linkid').click(); //Should alert('/testlocation'); } </script> <a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
Using onclick Event: The onclick event attribute works when the user click on the button. When mouse clicked on the button then the button acts like a link and redirect page into the given location. Using button tag inside <a> tag: This method create a button inside anchor tag.
We can use a button to link different pages. We will connect the url of the new page to the onclick event of the button. We can do this by using a form and a submit button but there is no point in using a form for a hyper linking of pages. So here are some examples of using buttons to link different pages.
You need to apply
the event handler in the context of that element:
var elem = document.getElementById("linkid"); if (typeof elem.onclick == "function") { elem.onclick.apply(elem); }
Otherwise this
would reference the context the above code is executed in.
The best way to solve this is to use Vanilla JS, but if you are already using jQuery, there´s a very easy solution:
<script type="text/javascript"> function doOnClick() { $('#linkid').click(); } </script> <a id="linkid" href="/testlocation" onclick="alert(this.href);">Testlink</a>
Tested in IE8-10, Chrome, Firefox.
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