The functionality of the tree grid bootstrap is not functioning properly when it is dynamically generated, but it works seamlessly when implemented statically

The code below functions correctly and provides the expected output.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TreeView_Table_Project.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <link href="Css/jquery.treegrid.css" rel="stylesheet" />

    <script src="Js/jquery.treegrid.js"></script>
    <script src="Js/jquery.treegrid.bootstrap3.js"></script>
    <script>
        $(document).ready(function () {
            $('.tree').treegrid();

        });



    </script>

    <style>
        tr, td {
            border: 2px solid black;
        }

        td {
            padding: 10px;
        }
    </style>

</head>
<body>


    <table class="tree">
        <tr class="treegrid-1">
            <td>Root node 1</td>
            <td>Additional info</td>
        </tr>
        <tr class="treegrid-2 treegrid-parent-1">
            <td>Node 1-1</td>
            <td>Additional info</td>
        </tr>

        <tr class="treegrid-3 treegrid-parent-1">
            <td>Node 1-1</td>
            <td>Additional info</td>
        </tr>
    </table>

</body>
</html>

The following code does not work when dynamically creating the table.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <link href="Css/jquery.treegrid.css" rel="stylesheet" />
    <script src="Js/jquery.jqGrid.min.js"></script>
    <script src="Js/jquery.treegrid.bootstrap3.js"></script>
    <script src="Js/jquery.treegrid.js"></script>
    <script>

        $(document).ready(function () {
            f1();
            $('.tree').treegrid();

        });


        function f1() {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "Bootstrap_TreeGrid.aspx/StateAnalysis",
                data: "{}",
                dataType: "json",
                success: function (Result) {
                    Result = Result.d;
                    drawTab(Result);
                },
                error: function (Result) {
                    alert("Error");
                }
            });
            function drawTab(data1) {

                var Result = data1;
                for (i = 0; i < Result.length; i++) {
                    var m = i + 1;
                    if (i == 0) {

                        $('<tr>', {
                            'class': 'treegrid-' + m,
                        }).appendTo($(".tree"));
                        //$(".tree").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it
                        //row.append($("<tr class='treegrid'+>Jurisdiction</tr>"));
                        $('<td>', {
                            text: 'phani',
                        }).appendTo($('.treegrid-' + m));


                    }
                    else {

                        $('<tr>', {
                            'class': 'treegrid-parent-1 treegrid-' + m,
                        }).appendTo($('.tree'));

                        //$(".tree").append(row); //this will append tr element to table... keep its reference for a while since we will add cels into it
                        //row.append($("<tr class='treegrid'+>Jurisdiction</tr>"));
                        $('<td>', {
                            text: 'phani',
                        }).appendTo($('.treegrid-' + m)); 
                    }


                }
            }
        }

    </script>


    <style>
        tr, td {
            border: 2px solid black;
        }

        td {
            padding: 10px;
        }


    </style>
</head>
<body> 

    <table class="tree">
    </table>
</body>
</html>

The provided code is not functioning correctly. It works with static data but encounters issues when attempting dynamic creation. Thank you in advance.

Answer №1

Update: The way the treegrid classes were assigned to the rows has been modified. It is now clear that the ID needs to be declared before assigning it to the parent element.

Here's the solution for you:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

  <head runat="server">
    <title></title>
    <script data-require="jquery@*" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link href="bootstrap.css" rel="stylesheet" />
    <link href="jquery.treegrid.css" rel="stylesheet" />

    <script src="jquery.treegrid.bootstrap3.js"></script>
    <script src="jquery.treegrid.js"></script>
    <script>

        $(document).ready(function () {
            f1();
            $('.tree').treegrid({
                expanderExpandedClass: 'glyphicon glyphicon-minus',
                expanderCollapsedClass: 'glyphicon glyphicon-plus'
            });
        });
            function f1() {
              var m = 0, line = '';
                for (i = 0; i < 3; i++) {
                    m = i + 1;
                    if (i == 0) {
                        line = '<tr class="treegrid-' + m + '">'
                          + '<td>Root node 1</td><td>Additional info</td></tr>';
                    }
                    else {
                        line = '<tr class="treegrid-' + m + ' treegrid-parent-' + i + '">'
                          + '<td>Node 1-1</td><td>Additional info</td></tr>';
                    }

                    $('.tree').append(line);
                }
            }

    </script>
    <style>
        tr, td {
            border: 2px solid black;
        }

        td {
            padding: 10px;
        }


    </style>
  </head>

  <body>
    <table class="tree"></table>
  </body>

</html>

You can view the updated version on plunker here. Let us know if this resolves your issue.

Answer №2

It is important to include the async: false option in your ajax function when initializing treegrid because the ajax result may not have returned yet.

 $.ajaxSetup({
    async : false
 });

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

The function google.script.run encounters an error when dealing with file inputs

For the past two years, my Google Apps Script connected to a spreadsheet has been working flawlessly. I created an HTML form to upload CSV and Excel files for processing and data loading into the spreadsheet. However, since March 2020, file uploading has b ...

What is the best way to transform the selected days of the week into comma-separated integers using JavaScript?

Users can select checkboxes for each day of the week. Below is an example JS object: {"mon":true,"tue":true,"wed":true,"thu":false,"fri":false,"sat":false,"sun":false} The goal is to convert these selections into a string of comma-separated values, with ...

The CSS3 Animation remains stationary

I've been attempting to animate my block element moving to the left using CSS animation shorthand property, but unfortunately, it's not working as expected. Here is my HTML: <div id="game"> <div id="block">&l ...

Storing data retrieved via AJAX into a WordPress table in JSON format

I have created a function and included some jQuery code to store form data submitted by users in a database table successfully. However, I am looking to modify it in order to save the data in JSON format instead. This will help prevent my WordPress table f ...

Tips for managing lag caused by large raw image re-renders in a React application

When trying to change the background position of a user-uploaded background image that is in raw Data URI format using CSS, I noticed that re-rendering becomes slow if the image size exceeds 1mb. This issue does not occur with smaller images. Is there a ...

Tips for identifying and handling a 400 bad request error in an HTTP response within an Angular 2 application

I attempted to handle the error 400 bad request in this manner: catch((error: any) => { if (error.status === 500) { return Observable.throw(new Error(error.status)); } else if (error.status === 400) { console.log( 'err ...

Section is obstructing the view of Other Section above

I am struggling to create a responsive design for these two sections, both of which display quite similarly in line. Here are the resolutions for desktop and tablet/mobile: https://i.sstatic.net/XWbSP.png https://i.sstatic.net/3KLyY.png I suspect the is ...

Jquery Ajax Request Error: SyntaxError caused by an unexpected token < in the code

I am attempting to retrieve a list of products through a GET request. The response I receive is in XML format with a 200 status code. Web Service: [WebMethod] [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] public List<product& ...

Choosing all components except for one and its descendants

I am searching for a method to choose all elements except for one specific element and its descendant, which may contain various levels of children/grandchildren or more. What I'm trying to accomplish is something like... $("*").not(".foo, .foo *").b ...

Using app.get('env') in local development and live production settings

var express = require('express'); var app = express(); var db_url; if(app.get('env') == "development"){ db_url = 'mongodb://127.0.0.1:27017/localhost'; }else{ db_url = 'something else'; } console.log(app.get(&apos ...

Adjust the position of all content below when the specific div slides down

I am attempting to create a notification div that smoothly slides down when active. The sliding effect is achieved through this script: <script type="text/javascript> $(document).ready(function(){ $('#notice').slideDown(1000); ...

Mapping an array based on specific conditions

When using my photo gallery app, I faced a challenge in mapping an array of images based on the user-selected album name. The current setup works perfectly for the 'Cambodia' album where all images are correctly logged in the console after mappin ...

Ways to verify the existence of a particular word within a nested array of objects

I have implemented a text input field and a send button for submitting the entered text. Utilizing the react-mention library, I am able to handle hashtags in the text. As the user types, if they include "#" it displays available hashtags from the data set. ...

steps for extracting arrays from ajax response and storing them as variables

For my HTML, I have already written the code to fetch the entire array. $('#btnSubmit').on('click', function () { array = []; $('.getOrders').each(function () { array = $(this).val(); //I added a con ...

The dialog box in CSS is extending too far down past the bottom of the screen, making it impossible to scroll and click on the buttons located

I am currently working on creating a dialog box with a text area using material UI. Unfortunately, when I input a significant amount of text, the dialog box ends up extending beyond the screen, making it impossible to scroll down to access the buttons. &l ...

The requested resource has No Access-Control-Allow-Origin for the XMLHttpRequest

I'm encountering a problem where I'm trying to access a file on another server that is running on port 3000 from a server on port 7777. The platform in use is node.js. XMLHttpRequest cannot load http://localhost:3000/register_user. No 'Acce ...

Refreshing Symfony2 values dynamically with ajax without the need for page reload

Let me start by saying that I am not a front-end expert, and this is my first attempt at working with ajax. My goal here is to update and display the new value without having to refresh the entire page. I only want to refresh the input field and its values ...

Why is it possible to apply column width to a div element, but not to a button?

This code functions properly and sets the button to a size 4: <div class="col-xs-4"> <button class="btn btn-block btn-primary">Like</button> </div> However, the following code does not work as expected: <div> <bu ...

Issue with Foundation4 Dropdown Persisting Despite Different Behavior Between Two CSS Files

My project involves having two CSS files, both compiled from SASS, that cater to right-to-left (RTL) and left-to-right (LTR) designs. Additionally, there are two separate HTML files, each referencing the corresponding CSS file: RTL: <link rel="stylesh ...

Ways to verify the $window variable in ng-if or ng-show

One variable named variable1 has been declared, and I am looking to validate this variable across all pages using ng-if or ng-show. ...