How to change href of <a> tag on button click through javascript
Without having a href
, the click will reload the current page, so you need something like this:
<a href="#" onclick="f1()">jhhghj</a>
Or prevent the scroll like this:
<a href="#" onclick="f1(); return false;">jhhghj</a>
Or return false
in your f1
function and:
<a href="#" onclick="return f1();">jhhghj</a>
....or, the unobtrusive way:
<a href="#" id="abc">jhg</a><a href="#" id="myLink">jhhghj</a><script type="text/javascript"> document.getElementById("myLink").onclick = function() { document.getElementById("abc").href="xyz.php"; return false; };</script>
Exactly what Nick Carver did there but I think it would be best if used the DOM setAttribute method.
<script type="text/javascript"> document.getElementById("myLink").onclick = function() { var link = document.getElementById("abc"); link.setAttribute("href", "xyz.php"); return false; }</script>
It's one extra line of code but find it better structure-wise.
remove href
attribute:
<a id="" onclick="f1()">jhhghj</a>
if link styles are important then:
<a href="javascript:void(f1())">jhhghj</a>