Reputation: 119
I am generating values into a table through ajax. This values are s. inside this roles there is an anchor that which would be in all this roles. This anchor tags have a class which I use to reference it with javascript.
The anchor tag in this roles have an onclick function referencing a javascript method, I am trying to use this method to get one of the attribute of the clicked anchor tag. But unfortunately I get the undefined error, when I click on the anchor tags in the role.
<tr>
<td>
<a href="#" onClick="JavaScript:filltransfercombo();" class="btn btn-default transferchat" data-operatorid="@avisitor.OperatorID" data-toggle="modal" data-target="#transferModal" title="Transfer chat">
<img src="~/Content/images/chaticons/transfer.png" height="20" width="20" />
</a>
</td>
</tr>
My intension is to collect this attribute -- data-operatorid. I want to use it for some manipulations in my javascript.
My javascript is below
<script type="text/javascript">
function filltransfercombo() {
var result = "";
var active = $('a').index(this);
var currentoperatorid = $(active).attr("data-operatorid"); //This is the id of the currently attending operator
console.log(currentoperatorid);
}
</script>
Upvotes: 0
Views: 505
Reputation: 3799
This can easily be done with jQuery.
Remove the "onClick" attribute on your anchors and instead bind a click function to the anchor tags (within the table only). Then add your processing code within that function.
Do something like this:
<script type="text/javascript">
$(document).ready(function() {
$('table tr td a').click(function() {
var result = "";
var currentoperatorid = $(this).data("operatorid"); //This is the id of the currently attending operator
console.log(currentoperatorid);
});
});
</script>
Natrually, you need to make sure the jQuery javascript library is also included on this page.
Upvotes: 0
Reputation: 16841
onclick
event does not need the javascript:
notation... You would put it in case you were setting the method on href
.
Also, from onclick
event you would have access to the this
variable, not from the method. You can, however, pass it as an argument, so:
<a href="#" onClick="filltransfercombo(this);" class="btn btn-default transferchat" data-operatorid="@avisitor.OperatorID" data-toggle="modal" data-target="#transferModal" title="Transfer chat">
and js:
function filltransfercombo(sender) {
var result = "";
var currentoperatorid = $(sender).attr("data-operatorid"); //This is the id of the currently attending operator
console.log(currentoperatorid);
}
Upvotes: 1