TR data-id coming Null Jquery

Asked

Viewed 46 times

0

I am unable to capture the data-id of my TR.

<script>
    function EditarContato() {
        var id = $(this).attr("data-id");
        debugger;
        var url = '@Url.Action("EditarContato","ContatoG", new{area= "Gerencial"})';
        $("#editarContato").load(url +"?id=" + id,
            function() {
                $("#editarContato").modal();
            });
    }
</script>
    <tr onclick="EditarContato()" data-id="@item.ContadoId">
                    <td>@item.Responsavel</td>
                    <td>@item.Funcao</td>
                    <td>@item.Celular</td>
                    <td>@item.Telefone</td>
                    <td>@item.Whatsapp</td>
    </tr>

id is always coming null, someone knows tell me what I’m doing wrong?

1 answer

1


The $(this) in var id = $(this).attr("data-id"); is not referring to the element clicked as the event in onclick is just calling the function. The function, in turn, has no way of knowing which element called it.

What you could do is send the element to the function through a this in onclick:

onclick="EditarContato(this)"

And in the function receive the this as a parameter, so that she knows which element called her, and uses it instead of this in $(this):

function EditarContato(elemento) {
   var id = $(elemento).attr("data-id");
   ...
  • Perfect, thank you, that’s exactly what it was!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.