Exploring the Best Methods to Retrieve the data-id in jstree JSON data

My goal is to retrieve the data-id from a dynamically generated tree form using JsTree (which has checkboxes), but unfortunately, my current approach isn't working. To iterate over the checkboxes and account for multiple selections, I am utilizing the $.each() function. Here's a snippet of my script:

$(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;
    }
});

Although I can successfully obtain the element with the following code (providing me only with the corresponding id):

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

The problem arises when attempting to access specific data attributes like data-id, which results in a null value:

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

I even tried to display all available information about the element by using:

let id = jQuery(this)

Surprisingly, there are several data attributes present, but they cannot be accessed. Can anyone provide some suggestions or insights on how to overcome this issue?

Answer №1

After some extensive searching, I have finally stumbled upon an effective solution! Interestingly enough, it's actually quite straightforward. All you need to do is utilize the .map() method to access and manipulate this data.

Take a look at this example:

$("button").on('click', function(){
    let items = obtain_items();
    alert(JSON.stringify(items));

});

function obtain_items(){
    let item_ids = [];
    let items = $('.tree').jstree('get_checked', true);
    $.each(items, function() {
        let id = $(this).map(function() { return this.data.id }).get().join();
        item_ids.push(id);
    }); 
    return item_ids;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for using Jquery to round up currency values

Is there a way to round up various currencies using jQuery? I have a specific requirement: 10.30 → 10 //Round down if below .5 10.60 → 11 //Round up if after .5 849.95 → 850 1,022.20 → 1022 ...

Toggle visibility of table row upon user click (HTML/JQuery)

Having an issue with showing or hiding table rows using jQuery. I would like it so that when a user clicks on a table row with id="jobtitle", the corresponding tr with class="texter" will either show up or hide if it is already displayed. This is my curre ...

Alter the color scheme of Fancybox's background

I am looking to create a transparent background color for Fancybox. The typical method involves using ".fancybox-skin" in CSS, however this will affect all fancyboxes and I require it to be unique. Therefore, the setting must be sent with wrapCSS. Fancyb ...

What is the appropriate utilization of the await keyword within concise if-else statements in JavaScript?

Along with transitioning away from jQuery, my main focus is to make my code more efficient. In large scale enterprise applications, the excessive use of jQuery and JavaScript can become problematic. I have decided to switch back to vanilla JavaScript for ...

How can I stop Jquery Mobile from processing the URL hash?

Currently implementing Jquery Mobile in a preexisting web application is posing a challenge. The issue arises as Jquery Mobile is interpreting all URL hashes by default. For example: mysite.com/#foo In this case, the hash 'foo' is being directe ...

Issues with JQuery onclick function on dropdown menu functionality not behaving as desired

Take a look at some example code here. Here's the HTML: <div> HTML<br> <li> <select id="Status" type="text"> <option value="New">New</option> <option value="Complete">Complete</option& ...

Manipulate images in real-time and insert custom text using JavaScript/jQuery

Within my possession is an image depicted above. My objective revolves around dynamically altering the values present at the occurrences of L, A, and B; to achieve this, I must eliminate or conceal L, A, and B while substituting them with numerical equiv ...

What is the method for eliminating PHP $_SESSION using AJAX?

I am facing an issue with removing an array within a PHP Session variable using AJAX. Here is the process I follow: HTML: <a href="#" onclick="delete_pix(false, '1', false, '1.jpg');">remove</a> JavaScript: functio ...

Demo showcasing the issue with the side navbar in Bootstrap not functioning as expected

I'm currently working on implementing a side nav bar using the code snippet from this link: However, when I integrate this code into my application, the left nav bar only extends to the height of the links, and the content area begins after the left ...

Utilize jQuery to showcase images on your webpage

There seems to be an issue with image display - sometimes the selected image does not show up until clicked a second time. Using jQuery $('#morefiles').change(function (event) { if (!(/\.(gif|jpg|jpeg|tiff|png)$/i).test($(this).val())) { ...

Comparing jquery ajax jsonp with angularjs $http json: A breakdown of two powerful ways

I have a scenario where I need to switch from using jquery to angularjs for a particular feature. Specifically, I am replacing jquery's ajax method with angularjs' $http method. This piece of code is responsible for enabling users to sign up for ...

The value property of the input element is returning as undefined

The input value entered is always returning undefined. Despite trying various solutions found in similar questions, my jQuery code continues to return undefined. jQuery: $( document ).ready(function() { $('#Input').keypress( function(e ...

What is the best way to eliminate leading and trailing spaces from a text input?

I'm currently working on troubleshooting a bug in an AngularJS application that involves multiple forms for submitting data. One of the issues I encountered is that every text box in the forms is allowing and saving leading and trailing white spaces ...

Filtering dynamically generated table rows using Jquery

I'm currently working on a project that involves filtering a dynamic table based on user input in a search bar. The table contains information such as name, surname, phone, and address of users. Using jQuery, I have created a form that dynamically ad ...

Modifying the design of a website in real-time using the EXPRESS.js and NODE.js frameworks

I successfully set up a simple website using node.js and express.js by following this helpful tutorial. My express implementation is structured like this with a jade file for the web interface. // app.js var express = require('express'), r ...

QuickFit, the jQuery plugin, automatically adjusts the size of text that is too large

I have incorporated the QuickFit library into my website to automatically resize text. However, I am running into an issue where the text is exceeding the boundaries of its containing div with a fixed size. This is something I need to rectify. This is ho ...

Ajax login feature not redirecting to login popup after successful login

When attempting to open a popup by clicking on the login window, a pop-up appears with a URL requesting username and password along with Google sign-in. However, when a user tries to log in using Google sign-in through the pop-up, it fails to redirect to ...

Avoiding metacharacters and utilizing them as a string variable for selection

For example, I have a variable called myid, and its value is "abc xyz". Then, I use a function to escape metacharacters and assign the result to another variable like this: var x = "#"+escapechars(myid);. The evaluated value of x is #abc\\xyz. ...

$http({method}) is malfunctioning while $http.get is functioning properly

Issue Description: While working on my project, I encountered an issue where using $http({ method : 'GET', url : data : ..... param works fine for both GET and POST requests. However, when the same method is used in JSFiddle, it blocks my reques ...

Postponed in JQUERY | AJAX

My requirement is to retrieve data using the "SetUnit()" function, which includes asynchronous AJAX services. I attempted to use Deferred as suggested in this link, but it did not work for my needs. Code...... Function function SetUnit(query) { var ...