Search code examples
jqueryjstree

How to get data-id in jstree JSON data


I am trying to get data-id from a tree form generated with a JsTree (checkbox form) but it's not working. I am using $.each(), because you can check more checkboxes. This is how my script looks like:

$(document).ready(function() {
    $(".js-save-button").on('click', function(){
        let boxes = check_checkboxes();
        alert(JSON.stringify(boxes));

    });

    function check_checkboxes(){
        let boxes_id = [];
        let boxes = $(".js-categories-checkboxtree").jstree("get_checked", true);
        $.each(boxes, function() {
            //let id = jQuery(this); //getting info
            //let id = (data.node.id); //not working
            let id = $(this).data('id'); //not working
            boxes_id.push(id);
        }); 
        return boxes_id;
    }
});

I can simply get this (but it returns not what I need I can just verify that I have the right element in this):

let id = $(this).attr('id');

But I can't get this (it returns null)

let id = $(this).data('id');

I tried to just alert everything I know about the element:

let id = jQuery(this)

and I can see there is a plenty of data attributes but I can't get any of them... Any ideas please?


Solution

  • So I have finally found a sollution! It's actually simple! You have to access these data with .map()!

    Like this:

    $(".js-save-product").on('click', function(){
        let boxes = check_checkboxes();
        alert(JSON.stringify(boxes));
    
    });
    
    function check_checkboxes(){
        let boxes_id = [];
        let boxes = $('.js-categories-checkboxtree').jstree('get_checked', true)
        $.each(boxes, function() {
            let id = $(this).map(function() { return this.data.id }).get().join();
            boxes_id.push(id);
        }); 
        return boxes_id;
    }