Search code examples
jquerycustom-data-attribute

Accessing data attribute using jquery returns undefined?


Inside my view i have a button as follow:

<button data-assigned-id="@IdUser" onclick="updateClick()" type="button" class="btn btn-sm btn-default"></button>

My div

<div id="partial_load_div">

</div>

Script

function updateClick() {
    var id = $(this).data('assigned-id');
    $('#partial_load_div').show();
    $('#partial_load_div').load('/Users/UpdatePartial?id=' + id);
}

The id is always shows as undefined, i checked and @IdUser has always value

then in chrome dev i got the error

GET http://localhost:19058/Users/UpdatePartial?id=undefined 400 (Bad Request)

Any idea how to fix this?


Solution

  • In your current script, $(this) refers to the Window object (not your button) which does not have a data- attribute so its undefined.

    You could solve this by passing the element to the function

    <button data-assigned-id="@IdUser" onclick="updateClick(this)" type="button" ... ></button>
    
    function updateClick(element) {
        var id = $(element).data('assigned-id');
        ....
    

    However a better approach is to use Unobtrusive Javascript rather than polluting your markup with behavior.

    <button data-assigned-id="@IdUser" id="mybutton" type="button" class="btn btn-sm btn-default"></button>
    
    $('#mybutton').click(function() {
        var id = $(this).data('assigned-id'); // $(this) refers to the button
        ....
    });