How to change the href
attribute value of an <a/>
tag through Javascript on button click ?
<script type="text/javascript">
function f1()
{
document.getElementById("abc").href="xyz.php";
}
</script>
<a href="" id="abc">jhg</a>
<a href="" id="" onclick="f1()">jhhghj</a>
This question is related to
javascript
href
attr
remove href
attribute:
<a id="" onclick="f1()">jhhghj</a>
if link styles are important then:
<a href="javascript:void(f1())">jhhghj</a>
<script type="text/javascript">
function f1(mHref)
{
document.getElementById("abc").href=mHref;
}
</script>
<a href="" id="abc">jhg</a>
<button onclick="f1("dynamicHref")">Change HREF</button>
Just give the dynamic HREF in Paramters
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.
I know its bit old post. Still, it might help some one.
Instead of tag,if possible you can this as well.
<script type="text/javascript">
function IsItWorking() {
// Do your stuff here ...
alert("YES, It Works...!!!");
}
</script>
`<asp:HyperLinkID="Link1"NavigateUrl="javascript:IsItWorking();"` `runat="server">IsItWorking?</asp:HyperLink>`
Any comments on this?
To have a link dynamically change on clicking it:
<input type="text" id="emailOfBookCustomer" style="direction:RTL;"></input>
<a
onclick="this.href='<%= request.getContextPath() %>/Jahanpay/forwardTo.jsp?handle=<%= handle %>&Email=' + document.getElementById('emailOfBookCustomer').value;" href=''>
A dynamic link
</a>
Here's my take on it. I needed to create a URL by collecting the value from a text box , when the user presses a Submit button.
<html>_x000D_
<body>_x000D_
_x000D_
Hi everyone_x000D_
_x000D_
<p id="result"></p>_x000D_
_x000D_
<textarea cols="40" id="SearchText" rows="2"></textarea>_x000D_
_x000D_
<button onclick="myFunction()" type="button">Submit!</button>_x000D_
_x000D_
<script>_x000D_
function myFunction() {_x000D_
var result = document.getElementById("SearchText").value;_x000D_
document.getElementById("result").innerHTML = result;_x000D_
document.getElementById("abc").href="http://arindam31.pythonanywhere.com/hello/" + result;_x000D_
} _x000D_
</script>_x000D_
_x000D_
_x000D_
<a href="#" id="abc">abc</a>_x000D_
_x000D_
</body>_x000D_
<html>
_x000D_
<a href="#" id="a" onclick="ChangeHref()">1.Change 2.Go</a>
<script>
function ChangeHref(){
document.getElementById("a").setAttribute("onclick", "location.href='http://religiasatanista.ro'");
}
</script>
Source: Stackoverflow.com