Search code examples
javascriptjquerysingle-page-applicationkendo-template

Access Dynamically Created Data Tag in Single Page Application


I have a single page application that is dynamically populating a div with list items that will call a function on click. I am trying to populate the data-tag dynamically and then access that within the appended list item.

The backslash in the $(\#documents) is there because this is a kendoUI-template that is being called by my route function.

The build tree function is being called within an Ajax success function once the data has been retrieved from the server. Any insight or help is appreciated!!!

   function buildTreeView(tree, jobCode){
       var treeHtml = "<div class='row'><div class='col-xs-12 col-sm-8 col-sm-offset-2'><div class='panel-group'><div class='panel panel-default'><div class='panel-heading'><h3 class='text-center'>View or Download Documents</h3></div><div class='panel-body'><ul class='list-group'>";
        for(var i =0;i < tree.length;i++){
          if(typeof tree[i] === 'object'){
            for(var ind = 0;ind < tree[i].length; ind++){
                //another element will be populated here
            }
          }else{
            treeHtml += "<li class='list-group-item viewDoc' data-docName='"+tree[i]+"' data-jobCode='"+jobCode+"'>"+tree[i]+"</li>";
          }
        }
        treeHtml += "</ul></div></div></div></div></div>";
        $('\#documents').append(treeHtml);
}

$(document).on("click", ".viewDoc", function(){
    var docName = $(this).data('docName');
    var jobCode = $(this).data('jobCode');
    console.log(docName);
    console.log(jobCode);
});

Solution

  • You are not able to access these data because the data attribute "docName" and "jobName" was normalized to lowercase.

    eg the html then looks like this:

    <li class="list-group-item viewDoc" data-docname="something" data-jobcode="something">something</li>
    

    Look here for better answer:

    In any case this will work:

    $(document).on("click", ".viewDoc", function(){
        var docName = $(this).data('docname');
        var jobCode = $(this).data('jobcode');
        console.log(docName);
        console.log(jobCode);
    });
    

    UPDATE: added jsfiddle