Reputation: 11
I have a simple series of anchor tags and I want the text of the anchor to appear in an input field.
How can I use Javascript to identify the clicked anchor rather than the first anchor tag, as in the attached script? Sum
<script type="text/javascript">
function test()
{
var var1 = document.getElementById('add2').innerHTML;
document.getElementById('add').value = var1;
}
</script>
</HEAD>
<BODY>
<FORM NAME="myform">
<INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
</FORM>
</BODY>
<br>
<br>
<a id="add2" onclick="test()" href="#" >Test1</a>
<br>
<a id="add2" onclick="test()" href="#" >Test2</a>
Upvotes: 0
Views: 426
Reputation: 166
You can do this using jquery. Just add class to the anchor tags.
<body>
<FORM NAME="myform">
<INPUT TYPE="text" ID="add" NAME="result" VALUE=""/>
</FORM>
<br>
<br>
<a id="add1" class="anchor" href="javascript:void(0)" >Test1</a>
<br>
<a id="add2" class="anchor" href="javascript:void(0)" >Test2</a>
</body>
$(document).ready(function() {
$(".anchor").click(function() {
var val = $(this).text();
$("#add").val(val);
});
});
You can see it working here. https://jsfiddle.net/ctzzfqm1/
Upvotes: 1
Reputation: 133403
Your code is not working as IDs in HTML must be unique. I would recommend to bind event using addEventListener
instead of ugly inline click handlers
window.onload = function() {
var elements = document.getElementsByClassName('add2');
for (var i = 0; i < elements.length; i++) {
elements[i].addEventListener('click', function() {
document.getElementById('add').value = this.innerHTML;
}, false);
}
}
<INPUT TYPE="text" ID="add" NAME="result" VALUE="" />
<br>
<a class='add2' href="#">Test1</a>
<br>
<a class='add2' href="#">Test2</a>
References:
Upvotes: 0
Reputation: 82241
You should pass clicked element object to method:
<a id="add2" onclick="test(this)" href="#" >Test1</a>
<a id="add2" onclick="test(this)" href="#" >Test2</a>
and then use the element context to access its text:
function test(obj){
document.getElementById('add').value = obj.innerHTML;
}
Upvotes: 0