How to Modify the Href Attribute of an Tag on Button Click Using JavaScript
Question:
How can you change the href attribute value of an tag through JavaScript on button click?
Answer:
To alter the href attribute of an tag when a button is clicked, the following methods can be employed:
Option 1: Using an Empty href
Add an empty href attribute to the tag:
<code class="html"><a href="" id="abc">jhg</a></code>
Option 2: Preventing Page Reload
Include the code below within the href attribute to prevent page reload:
<code class="html"><a href="#" onclick="f1();">jhhghj</a></code>
Option 3: Returning False from the Function
In the f1() function, return false and call it from the href like this:
<code class="html"><a href="#" onclick="return f1();">jhhghj</a></code>
Option 4: Unobtrusive Way
Use the following JavaScript to modify the href attribute without inline event handlers:
<code class="html"><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></code>
The above is the detailed content of How to Change the `href` Attribute of an `` Tag on Button Click with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!