jqueryunobtrusive

read unobtrusive data using jQuery


I do not find any example how to read unobtrusive data using jQuery. For example below

<a id="deleteFile" href="" data="123">Delete file</a>

I would like to read data attribute from a element. How to do that?


Solution

  • The best way is to just get the element attribute

    $('#deleteFile').attr('data');
    

    If your using a newish jquery library version (higher than 1.6 i belive) you can also use HTML5 data attributes with jQuery's data(). Change your anchor link to something like

    <a id="deleteFile" href="" data-fileid="123">Delete file</a>
    

    then you can use

    $('#deleteFile').data('fileid');
    

    However do NOT use them interchangeably, use one method only otherwise you may incur issues later on as jQuerys data() will only READ the data attributes then store them in an internal cache. If you change anything via data(), it will not be changed in the actual tag attribute meaning data() and attr() will return different results thereafter