Accessing data attribute using jquery returns undefined?

In my view, I have a button:

<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 identifier is always displayed as undefined, I checked and @IdUseralways matters

then in chrome dev I got an error

GET http: // localhost: 19058 / Users / UpdatePartial? Id = undefined 400 (failed request)

Any idea how to fix this?

+4
source share
2 answers

In the current script, it $(this)refers to an object Window(not your button) that does not have an attribute data-, therefore its undefined.

This can be solved by passing a function element.

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

Javascript, .

<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
    ....
});
+2

data() - . , :

var id = $(this).data('assignedId');

docs on data() :

jQuery 1.4.3 HTML- jQuery. jQuery 1.6, W3C HTML5 .

, HTML:

<div data-role="page" data-last-value="43" data-hidden="true" data-options='{"name":"John"}'></div>

jQuery- .

$( "div" ).data( "role" ) === "page";
$( "div" ).data( "lastValue" ) === 43;
$( "div" ).data( "hidden" ) === true;
$( "div" ).data( "options" ).name === "John";

data-last-value . , jQuery , ​​ , - . , lastValue .


, click. $(this), jquery. :

<button data-assigned-id="works" id="button">
clickme</button>

$(window).ready(function() {
     //bind the event using jquery not the onclick attribute of the button
     $('#button').on('click', updateClick);

});


function updateClick() {
    alert($(this).data('assignedId'));
}

+5

All Articles