OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

TypeError: Cannot read properties of null (reading '2') with jQuery NestedSortable's toArray()

  • Thread starter Thread starter Szymon
  • Start date Start date
S

Szymon

Guest
I'm encountering a persistent issue with the jQuery NestedSortable plugin, specifically with the toArray() method, which is throwing a TypeError: Cannot read properties of null (reading '2') during a drag-and-drop operation on a nested list. Here is a detailed description of the problem:

Context:

I am using the NestedSortable plugin to manage a hierarchy of categories and subcategories on a webpage, where users can rearrange categories through drag-and-drop. The goal is to capture the new arrangement and save it back to the server.

Issue:

Whenever I attempt to update the list of categories after changes made by the user (e.g., dragging elements to new positions), I receive a TypeError at the point where the toArray() method of NestedSortable is called. This error occurs specifically when the update event is triggered.

Error Message:

javascript

Code:
TypeError: Cannot read properties of null (reading '2')

This error originates deep within the NestedSortable plugin's codebase, as evidenced by the stack trace, and occurs right after the drag operation is completed.

Code Snippet:

Here is the jQuery snippet where toArray() is invoked:

javascript

Code:
update: function (event, ui) {
  try {
    var nestedCategories = $(this).nestedSortable("toArray", {
      startDepthCount: 0,
      attribute: "data-id",
    });
    console.log("Nested Categories after update:", nestedCategories);
  } catch (error) {
    console.error("Error in nestedSortable toArray:", error);
    console.log("Current state of list:", $(this).html());
  }
}

here is full js code:

Code:
$(document).ready(function () {
  function initializeSortable() {
    $(".sortable").nestedSortable({
      handle: "div",
      items: "li",
      toleranceElement: "> div",
      isTree: true,
      expandOnHover: 700,
      startCollapsed: true,
      placeholder: "placeholder",
      listType: "ol",
      forcePlaceholderSize: true,
      update: function (event, ui) {
        var nestedCategories = $(this).nestedSortable("toArray", {
          startDepthCount: 0,
          attribute: "data-id",
        });
        console.log("Nested Categories after update:", nestedCategories);

        nestedCategories.forEach((category) => {
          const categoryName = $(`#category_${category.id} > div`)
            .text()
            .trim();
          console.log(`Category ID: ${category.id}, Name: ${categoryName}`);
        });
      },
    });
  }

  initializeSortable();

  $("#addCategoryButton").on("click", function () {
    const categoryName = $("#newCategoryName").val().trim();
    if (!categoryName) return;

    const newCategoryId = new Date().getTime();
    const newCategory = $(`
      <li id="category_${newCategoryId}" class="category" data-id="${newCategoryId}">
        <div>${categoryName}</div>
      </li>
    `);
    $("#categories").append(newCategory);
    $("#newCategoryName").val("");
    initializeSortable();
  });

  $("#saveCategoriesButton").on("click", function () {
    const nestedCategories = $("#categories").nestedSortable("toArray", {
      startDepthCount: 0,
      attribute: "data-id",
    });
    console.log("Nested Categories on save:", nestedCategories);

    const categories = nestedCategories
      .filter((category) => category.item_id)
      .map((category) => ({
        id: parseInt(category.item_id),
        name: $(`#category_${category.item_id} > div`).text().trim(),
        parent_id: category.parent_id ? parseInt(category.parent_id) : null,
        depth: category.depth,
      }));

    console.log("Categories to send:", categories);

    $.ajax({
      url: "update_category_order.php",
      method: "POST",
      contentType: "application/json",
      data: JSON.stringify({ categories: categories }),
      success: function (response) {
        console.log("Save response:", response);
      },
      error: function (error) {
        console.error("Save error:", error);
      },
    });
  });
});

I've checked if there are any DOM elements missing or incorrectly identified before calling toArray(). Additional logging was added to monitor the output of toArray() and to ensure that all expected elements are present and accounted for in the DOM. I considered the possibility that other scripts might be modifying the DOM in a way that affects NestedSortable but found no such interference.

What could be causing this error in the NestedSortable plugin, and how can it be resolved? Is there a known issue with the plugin when handling certain types of nested structures or a particular way to configure the plugin to avoid such errors?

<p>I'm encountering a persistent issue with the jQuery NestedSortable plugin, specifically with the toArray() method, which is throwing a TypeError: Cannot read properties of null (reading '2') during a drag-and-drop operation on a nested list. Here is a detailed description of the problem:</p>
<p>Context:</p>
<p>I am using the NestedSortable plugin to manage a hierarchy of categories and subcategories on a webpage, where users can rearrange categories through drag-and-drop. The goal is to capture the new arrangement and save it back to the server.</p>
<p>Issue:</p>
<p>Whenever I attempt to update the list of categories after changes made by the user (e.g., dragging elements to new positions), I receive a TypeError at the point where the toArray() method of NestedSortable is called. This error occurs specifically when the update event is triggered.</p>
<p>Error Message:</p>
<p>javascript</p>
<pre><code>TypeError: Cannot read properties of null (reading '2')
</code></pre>
<p>This error originates deep within the NestedSortable plugin's codebase, as evidenced by the stack trace, and occurs right after the drag operation is completed.</p>
<p>Code Snippet:</p>
<p>Here is the jQuery snippet where toArray() is invoked:</p>
<p>javascript</p>
<pre><code>update: function (event, ui) {
try {
var nestedCategories = $(this).nestedSortable("toArray", {
startDepthCount: 0,
attribute: "data-id",
});
console.log("Nested Categories after update:", nestedCategories);
} catch (error) {
console.error("Error in nestedSortable toArray:", error);
console.log("Current state of list:", $(this).html());
}
}
</code></pre>
<p>here is full js code:</p>
<pre><code>$(document).ready(function () {
function initializeSortable() {
$(".sortable").nestedSortable({
handle: "div",
items: "li",
toleranceElement: "> div",
isTree: true,
expandOnHover: 700,
startCollapsed: true,
placeholder: "placeholder",
listType: "ol",
forcePlaceholderSize: true,
update: function (event, ui) {
var nestedCategories = $(this).nestedSortable("toArray", {
startDepthCount: 0,
attribute: "data-id",
});
console.log("Nested Categories after update:", nestedCategories);

nestedCategories.forEach((category) => {
const categoryName = $(`#category_${category.id} > div`)
.text()
.trim();
console.log(`Category ID: ${category.id}, Name: ${categoryName}`);
});
},
});
}

initializeSortable();

$("#addCategoryButton").on("click", function () {
const categoryName = $("#newCategoryName").val().trim();
if (!categoryName) return;

const newCategoryId = new Date().getTime();
const newCategory = $(`
<li id="category_${newCategoryId}" class="category" data-id="${newCategoryId}">
<div>${categoryName}</div>
</li>
`);
$("#categories").append(newCategory);
$("#newCategoryName").val("");
initializeSortable();
});

$("#saveCategoriesButton").on("click", function () {
const nestedCategories = $("#categories").nestedSortable("toArray", {
startDepthCount: 0,
attribute: "data-id",
});
console.log("Nested Categories on save:", nestedCategories);

const categories = nestedCategories
.filter((category) => category.item_id)
.map((category) => ({
id: parseInt(category.item_id),
name: $(`#category_${category.item_id} > div`).text().trim(),
parent_id: category.parent_id ? parseInt(category.parent_id) : null,
depth: category.depth,
}));

console.log("Categories to send:", categories);

$.ajax({
url: "update_category_order.php",
method: "POST",
contentType: "application/json",
data: JSON.stringify({ categories: categories }),
success: function (response) {
console.log("Save response:", response);
},
error: function (error) {
console.error("Save error:", error);
},
});
});
});
</code></pre>
<p>I've checked if there are any DOM elements missing or incorrectly identified before calling toArray().
Additional logging was added to monitor the output of toArray() and to ensure that all expected elements are present and accounted for in the DOM.
I considered the possibility that other scripts might be modifying the DOM in a way that affects NestedSortable but found no such interference.</p>
<p>What could be causing this error in the NestedSortable plugin, and how can it be resolved? Is there a known issue with the plugin when handling certain types of nested structures or a particular way to configure the plugin to avoid such errors?</p>
 

Latest posts

G
Replies
0
Views
1
Gamal Othman
G
Top