I have html code like this:
<a id="abc_1" name="link_1" href=""
onclick="updateLink(this.id);">Test Link</a>
My Javascript function is like this:
function updateLink(a){
var newurl = document.location.href "+" + a.valueOf();
return newurl;
}
I want to direct the user to this newurl on click of link.
How to do it?
Note: I have seen an example with use of <div>
tag, but I need it in <a href>
tag.
I have html code like this:
<a id="abc_1" name="link_1" href=""
onclick="updateLink(this.id);">Test Link</a>
My Javascript function is like this:
function updateLink(a){
var newurl = document.location.href "+" + a.valueOf();
return newurl;
}
I want to direct the user to this newurl on click of link.
How to do it?
Note: I have seen an example with use of <div>
tag, but I need it in <a href>
tag.
-
2
location.href = newurl
should work – tymeJV Commented Jan 20, 2016 at 19:59 - you aren't redirecting them with that function. like @tymeJV said you need to set the location.href of the page. – Devin Prejean Commented Jan 20, 2016 at 20:06
- I removed return and tried location.href = newurl, but its not working, if I do alert(newurl), it shows the updated url but page is just getting refreshed. – User2403 Commented Jan 20, 2016 at 20:18
- Yes you are correct. I found out my mistake, I havent used href="#". Sorry I am new to web development and Thank a Lot – User2403 Commented Jan 20, 2016 at 20:32
- @User2403 That's correct, a link without an href does not get treated as a link jsfiddle/4n1rfwch/1 – Ruan Mendes Commented Jan 20, 2016 at 20:58
2 Answers
Reset to default 2I assume that the anchor attribute id or name contains information about the new URL.
Check out this example:
<a href="#" id="abc_1" name="link_1" onclick="updateLink(this)" >Test Link</a>
<script>
function updateLink(a) {
var newurl = "";
//You could retrieve the object name
newurl = a.getAttribute("name");
//Or, retrieve the id
newurl = a.getAttribute("id");
//redirect
location.href = newurl;
}
</script>
One way is to change the href attribute from the click handler
window.updateLink = function (a){
// This won't work in this example because this frame
// is set 'X-Frame-Options' to 'SAMEORIGIN'.
// However, the error message displayed in the console is indication
// that it indeed tried to navigate to the URL I gave it
a.setAttribute('href', 'http://www.google.?q=' + a.id);
}
<a href="#" id="http://www.google." onclick="updateLink(this)" >Test</a>