Demsaas Demsaas - 25 days ago 11
Javascript Question

How to get div that fired event if i have function onclick on it?

Given this HTML code:

<td role-id="@Model.Id">
@Model.Name
<div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole()'></div>
</td>


I need to retrieve
role-id
when clicking on the div.

JS code:

function UpdateRole() {
$("#ModalUser").show();
var role_id = $(this).parent().attr("role-id");
var user_id = $(this).parent().parent().attr("user-id");
console.log(role_id);
console.log(user_id);
};


Both values are
undefined
, how can I get
role-id
without this?

Answer

Better approach is to use jQuery event binding, but using your approach, pass this context from called function:

Problem: In your example, this is not the element on which event is invoked but window!

function UpdateRole(that) {
  $("#ModalUser").show();
  var role_id = $(that).parent().attr("role-id");
  var user_id = $(that).parent().parent().attr("user-id");
  console.log(role_id);
  console.log(user_id);
};
<td role-id="@Model.Id">
  @Model.Name
  <div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole(this)'></div>
</td>

Using jQuery event-binding:

function UpdateRole() {
  $("#ModalUser").show();
  var role_id = $(this).parent().attr("role-id");
  var user_id = $(this).parent().parent().attr("user-id");
  console.log(role_id);
  console.log(user_id);
}
$('.update_user').on('click', UpdateRole);
<td role-id="@Model.Id">
  @Model.Name
  <div class='glyphicon glyphicon-edit update_user' onclick='UpdateRole(this)'></div>
</td>
Comments