Utilizing JavaScript for Interactive Check/Uncheck Feature in TreeView Nodes

I am currently utilizing the following JavaScript for implementing Check/Uncheck functionality for TreeView nodes checkboxes. The treeview contains three levels: parent, child, and siblings. Although the JavaScript code functions properly, I am in need of assistance to modify it so that the siblings level can be checked and unchecked independently without affecting the parent and child check/uncheck functionalities. Can someone please help me with making the necessary modifications to the code?

<script type="text/javascript">
        function OnTreeClick(evt) {
            var src = window.event != window.undefined ? window.event.srcElement : evt.target
            var isChkBoxClick = (src.tagName.toLowerCase() == "input" && src.type == "checkbox");
            if (isChkBoxClick) {
                var parentTable = GetParentByTagName("table", src);
                var nxtSibling = parentTable.nextSibling;
                if (nxtSibling && nxtSibling.nodeType == 1)//check if nxt sibling is not null & is an element node
                {
                    if (nxtSibling.tagName.toLowerCase() == "div") //if node has children
                    {
                        //check or uncheck children at all levels
                        CheckUncheckChildren(parentTable.nextSibling, src.checked);
                    }
                }
                //check or uncheck parents at all levels
                CheckUncheckParents(src, src.checked);
            }
        }

        function CheckUncheckChildren(childContainer, check) {
            var childChkBoxes = childContainer.getElementsByTagName("input");
            var childChkBoxCount = childChkBoxes.length;
            for (var i = 0; i < childChkBoxCount; i++) {
                childChkBoxes[i].checked = check;
            }
        }

        function CheckUncheckParents(srcChild, check) {
            var parentDiv = GetParentByTagName("div", srcChild);
            var parentNodeTable = parentDiv.previousSibling;

            if (parentNodeTable) {
                var checkUncheckSwitch;

                if (check) //checkbox checked
                {
                    checkUncheckSwitch = true;
                }
                else //checkbox unchecked
                {
                    var isAllSiblingsUnChecked = AreAllSiblingsUnChecked(srcChild);
                    if (!isAllSiblingsUnChecked)
                        checkUncheckSwitch = true;
                    else
                        checkUncheckSwitch = false;
                }

                var inpElemsInParentTable = parentNodeTable.getElementsByTagName("input");
                if (inpElemsInParentTable.length > 0) {
                    var parentNodeChkBox = inpElemsInParentTable[0];
                    parentNodeChkBox.checked = checkUncheckSwitch;
                    //do the same recursively
                    CheckUncheckParents(parentNodeChkBox, checkUncheckSwitch);
                }
            }
        }

        function AreAllSiblingsUnChecked(chkBox) {
            var parentDiv = GetParentByTagName("div", chkBox);
            var childCount = parentDiv.childNodes.length;
            for (var i = 0; i < childCount; i++) {
                if (parentDiv.childNodes[i].nodeType == 1) //check if the child node is an element node
                {
                    if (parentDiv.childNodes[i].tagName.toLowerCase() == "table") {
                        var prevChkBox = parentDiv.childNodes[i].getElementsByTagName("input")[0];
                        //if any of sibling nodes are not checked, return false
                        if (prevChkBox.checked) {
                            return false;
                        }
                    }
                }
            }
            return true;
        }

        //utility function to get the container of an element by tagname
        function GetParentByTagName(parentTagName, childElementObj) {
            var parent = childElementObj.parentNode;
            while (parent.tagName.toLowerCase() != parentTagName.toLowerCase()) {
                parent = parent.parentNode;
            }
            return parent;
        }
    </script>

Answer №1

// trvTest.Attributes.Add("onclick", "OnCheckBoxCheckChanged(event)"); 

function OnCheckBoxCheckChanged(event)
        {
            var element = window.event.srcElement;
            var treeNodeFound = false;
            var checked;
            if (element.tagName == "INPUT" && element.type == "checkbox") 
            {
                var node = element;
                checked = node.checked;
                do
                {
                    element = element.parentElement;
                } 

                while (element.tagName != "TABLE")
                var parentLevel = element.rows[0].cells.length;
                var parentNode = element.rows[0].cells[0];
                var tableList = element.parentElement.getElementsByTagName("TABLE");
                var totalTables = tableList.length
                if (totalTables >= 1)
                {
                    for (i=0; i < totalTables; i++)
                    {
                        if (tableList[i] == element)
                        {
                            treeNodeFound = true;
                            i++;
                            if (i == totalTables)
                            {
                                return;
                            }
                        }
                        if (treeNodeFound == true)
                        {
                            var childLevel = tableList[i].rows[0].cells.length;
                            if (childLevel > parentLevel)
                            {
                                var cell = tableList[i].rows[0].cells[childLevel - 1];
                                var inputs = cell.getElementsByTagName("INPUT");
                                if (inputs.length > 0)
                                    inputs[0].checked = checked;
                            }
                            else
                            {
                                return;
                            }
                        }
                    }
                }
            }
        }

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 Emphasizing a Row in a Table Using a Specific Value

Currently, I am engaged in creating an educational YouTube tutorial that delves into Google App Script and Google Sheets. I have been attempting various methods to highlight a row containing the word "ABSENT", but all my endeavors have proven to be unsucc ...

What is the method for defining the maximum selectable month in mtz.monthpicker?

(edited) Currently, I am utilizing the jquery.mtz.monthpicker plugin along with jquery. My goal is to limit the selection of future months, but it appears that there are no options similar to 'maxDate' like in jquery.ui.datepicker. $('inp ...

The Next Js API is experiencing difficulties resolving

I'm just starting out with back-end development so I could use some assistance with my current project. I am working on a next.js application that applies a black and white filter to an image when it is uploaded. In the index.js file, once a file is s ...

The child component is set to auto scroll without affecting the parent component

Check it out here: https://jsfiddle.net/wh6r4ybe/42/ const historyEndRef = useRef(null); const scrollToBottom = () => { historyEndRef.current.scrollIntoView({ behavior: "smooth" }); }; useEffect(() => { scrollToBottom(); }); I am trying to a ...

What is the method for determining profit as a percentage?

I need some help with a basic question. I have two variables, 'a' and 'b'. Variable A represents the money I receive from a customer, while variable B represents the money I will pay to a carrier. For example, if I receive $1000 from a ...

What is the proper way to insert a line break within a string in HTML code?

Trying to simplify my code, I've turned to using Nunjucks to pass a group of strings to a function that will then display them. This is what it looks like: {% macro DisplayStrings(strings) %} {% for item in strings %} <div>{{ item.strin ...

Tips for managing Hiddenfield values in codebehind and preserving them on the CS Page even after the Session time limit expires

In my aspx page, I am working with hidden fields to handle certain values. The goal is to return the entire result set to the aspx.cs page. If this result set is returned within the session time-out period, the save operation is successful. However, if i ...

Execute the onclick function of an element using JQuery in an ASP.NET application

My ASP.NET server control is customized to inherit from CheckBoxList, rendering the controls with a UL and LIs and set to AutoPostBack. Here is the markup I am using: <div id="foo"> <ul> <li> <input id="..." ...

Transform the string with binary hexadecimal characters in ASCII into a Buffer

Currently, I am utilizing node.js for my project. Within my code, there is a string variable called msg_str that contains the value "0102ab00aabb00". My goal is to convert this ASCII binary hex representation into a Buffer and have it displayed as <01 ...

Dynamic element validation in JavaScript

Is there a way to validate text inputs that are generated dynamically? I currently have a "add more" link that adds new text inputs, and a link to remove them. Each input has its own unique ID. In addition, validation should require at least two text box ...

The step-by-step guide for replacing the extJs Controller component

I have developed a versatile component that is being utilized across different products. In this case, I have a generic window and window controller which I am customizing to fit our specific product requirements. This is my generic window: Ext.define(&a ...

What is the process of manually loading webpack async chunks in the event that a dynamic import fails to load the file?

Async chunks in webpack can be created by using Dynamic Imports (for example: import('./ModuleA.js');). If the dynamic chunks fail to load, I want to retry loading them from another location. After grappling with the issue and delving into babel ...

Uncovering the Mystery of AJAX and JSON in jQuery and NodeJS

Currently, I'm facing a challenge with an ajax function that sends a json to a nodejs route. I need to extract the selected values from 4 button-groups named quality, costeffectiveness, deliveryscope, and rating. Each button-group consists of 5 radio- ...

Extracting IDs from an array response in Vue.js

Hey there, I have a scenario where I am fetching response data using Vue.js with Axios from Laravel: Here is my example method in Vue.js: getApps(page = 1){ axios.get('/api/getappforms') .then(response => { apps = res ...

How can I pan/move the camera in Three.js using mouse movement without the need to click?

I am currently working on panning the camera around my scene using the mouse. I have successfully implemented this feature using TrackballControls by click and dragging. function init(){ camera = new THREE.PerspectiveCamera(45,window.innerWidth / windo ...

Does creating a new schema for each functional call have an impact on performance?

For each function call, I need to create a new schema based on my requirements. This approach seems to work, but I have concerns about its impact on performance. Here is my code: app.post('/', (req, res)=> { const {query, data} = ...

Obtain settings from the appsettings.json file

In ASP.NET Core, the application configuration is now found in the appsettings.json file. I want to extract the connection strings specifically from this appsettings.json: { "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "De ...

Choose an element at random

I am trying to figure out how to select all div elements with the same class of "dot" under a parent div in JavaScript. Here is an example structure: <div id="dots"> <div class="dot"> . </div> <div class="dot"> . </div> ...

Can anyone suggest methods for displaying query data from a JSON file using HTML?

After countless hours of searching through various forums, I have attempted numerous methods to display query data from a JSON file onto an HTML page. My initial attempt was using XmlHttpRequest, which yielded no results. I then tried utilizing jQuery, sp ...

Update the content within a div based on the selected option from a dropdown menu or

Is there a way to change the displayed text based on user input or selected option? By default, the text shown is "Aa Bb Cc Dd Ee...", but it can be changed by selecting different options. If text is typed into the input field, the displayed text will up ...