...

View Full Version : Access a href elements from Javascript



anki2610
03-17-2009, 05:15 PM
Hi,

I have a requirement to list out a number of values as links (dynamically).
Onclicking any of these links , the value of this link should be set in a hidden form variable from javascript.

For eg: if the list of links are

abc1234
pqr12334
fgf23344
(The number of values in this list is dynamic)
I should be able to get abc1234 from the hidden variable if I click on the first link.

Pls help
Thanks

freedom_razor
03-17-2009, 05:50 PM
list out a number of values as links (dynamically).
Onclicking any of these links , the value of this link should be set in a hidden form variable from javascript.

That's exactly your assignment or are there more details?

Philip M
03-17-2009, 05:55 PM
I don't think that it is possible to capture the text content of a link (but happy to be proved wrong).
This is probably the best you can do:-



<a href="#" onclick = "myFunction('abc12345')">abc12345</a>
<a href="#" onclick = "myFunction('pqr12344')">pqr12344</a>
<a href="#" onclick = "myFunction('fgf23344')">fgf23344</a>

<script type = "text/javascript">

function myFunction (which) {
alert (which);
}



"The only thing to do with good advice is pass it on. It is never any use to oneself." - Oscar Wilde (Irish Poet, Novelist, Dramatist and Critic, 1854-1900)

freedom_razor
03-17-2009, 06:11 PM
<body>
<a href="#" onclick = "myFunction('abc12345')">abc12345</a>
<a href="#" onclick = "myFunction('pqr12344')">pqr12344</a>
<a href="#" onclick = "myFunction('fgf23344')">fgf23344</a><br />
<script type = "text/javascript">
var a=document.body.getElementsByTagName('a');
for(i=0;i<a.length;i++){
document.write(a[i].innerHTML+'<br />')
}
</script>
</body>

Eldarrion
03-17-2009, 06:15 PM
Or.....



<script type="text/javascript">
window.onload = function() {
var temp = document.getElementsByTagName("a");
for (i=0;i< temp.length;i++) {
temp[i].onclick = clicky;
}
}
function clicky() {
var blah = this.innerHTML;
alert(blah);
return false;
}
</script>


Just replace the alert(marked in red) with whatever you want it to do with the variable... and you should be all set. Each click on a link on the document will do whatever you need it doing. Enjoy.

EDIT: This was tested with the following HTML mark-up:



<a href="#">Test 1</a>
<a href="#">Something else</a>
<a href="#">Oh my god!</a>


P.S. Philip, read my signature. :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum