Accessing data attribute using jquery returns undefined? -


inside view have button 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 shows undefined, checked , @iduser has value

then in chrome dev got error

get http://localhost:19058/users/updatepartial?id=undefined 400 (bad request)

any idea how fix this?

in current script, $(this) refers window object (not button) not have data- attribute undefined.

you solve passing element function

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

however better approach use unobtrusive javascript rather polluting markup 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 button     .... }); 

Comments