The checkbox is displayed as selected after being clicked in conjunction with another checkbox

In the tree structure, there are checkboxes that behave strangely when clicked. I have already read a similar discussion here.

The problem I am encountering is that when I click on an item, it gets checked but the console does not show it as checked immediately. Instead, when I click on another item, the previously clicked item shows up as checked in the list. The currently selected item only shows up as checked after clicking on another item.

So, the functionality is working, but not when I actually click on the item, rather it updates after clicking on another item.

$(document).ready(function() {
  var toggle = function() {
    //var id = $(this).parent().find('input:first')[0].id;
    //$("#"+id).find("input").prop('checked', 'checked');
    //$(this).find("input").prop('checked', true);
    //console.log($(this).parent().find('input:first')[0].id);
    if (!$(this).closest("li").find("ul:first").is(":visible") && $(this).closest("li").is(":visible")) {
      //console.log("checked");
      $(this).parent('li:has(>ul)').find("span:first").removeClass("glyphicon glyphicon-plus-sign").addClass("glyphicon glyphicon-minus-sign");
    } else {
      //console.log("unchecked");
      $(this).parent('li:has(>ul)').find("span:first").removeClass("glyphicon glyphicon-minus-sign").addClass("glyphicon glyphicon-plus-sign");
    }
    $(this).parent().children().toggle();
    $(this).toggle();
    console.log($('input[name="level1"]:checked'));
    console.log($('input[name="level2"]:checked'));
    console.log($('input[name="level3"]:checked'));
  };
  $(".Collapsable").click(toggle);
  $(".Collapsable").each(toggle);
  $('.tree li:not(:has(>ul))').find("span:first").addClass("glyphicon glyphicon-bookmark");
});
ul.tree,
ul.tree ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

ul.tree ul {
  margin-left: 0px;
}

ul.tree li {
  margin: 0;
  margin-left: 20px;
  padding: 0 7px;
  line-height: 20px;
  color: #369;
  font-weight: bold;
  border-left: 1px solid rgb(100, 100, 100);
}

ul.tree li:last-child {
  border-left: none;
}

ul.tree li:before {
  position: relative;
  top: -0.3em;
  height: 1em;
  width: 12px;
  color: white;
  border-bottom: 5px solid rgb(100, 100, 100);
  content: "";
  display: inline-block;
  left: -7px;
}

ul.tree li:last-child:before {
  border-left: 1px solid rgb(100, 100, 100);
}

input[type=checkbox] {
  position: absolute;
  margin-top: 4px\9;
  margin-left: -20px;
  visibility: hidden;
}

input[type=checkbox]+label {
  display: initial;
}

input[type=checkbox]:checked+label {
  color: #f00;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="container">
  <div class="row">
    <ul class="tree">
      <li>
        <input type="checkbox" name="level1" id="Parent_1">
        <label class="Collapsable" for="Parent_1">
          <span></span> Parent_1
        </label>
        <ul>
          <li>
            <input type="checkbox" name="level2" id="Child_1_1">
            <label class="Collapsable" for="Child_1_1">
              <span></span> Child_1_1
            </label>
          </li>
          <li>
            <input type="checkbox" name="level2" id="Child_1_2">
            <label class="Collapsable" for="Child_1_2">
              <span></span> Child_1_2
            </label>
            <ul>
              <li>
                <input type="checkbox" name="level3" id="Grand_Child_1_2_1">
                <label class="Collapsable" for="Grand_Child_1_2_1">
                  <span></span> Grand_Child_1_2_2
                </label>
              </li>
              <li>
                <input type="checkbox" name="level3" id="Grand_Child_1_2_2">
                <label class="Collapsable" for="Grand_Child_1_2_2">
                  <span></span> Grand_Child_1_2_2
                </label>
              </li>
            </ul>
          </li>
        </ul>
      </li>
      <li>
        <input type="checkbox" name="level1" id="Parent_2">
        <label class="Collapsable" for="Parent_2">
          <span></span> Parent_2
        </label>
        <ul>
          <li>
            <input type="checkbox" name="level2" id="Child_2_1">
            <label class="Collapsable" for="Child_2_1">
              <span></span> Child_2_1
            </label>
          </li>
          <li>
            <input type="checkbox" name="level2" id="Child_2_2">
            <label class="Collapsable" for="Child_2_2">
              <span></span> Child_2_2
            </label>
            <ul>
              <li>
                <input type="checkbox" name="level3" id="Grand_Child_2_2_1">
                <label class="Collapsable" for="Grand_Child_2_2_1">
                  <span></span> Grand_Child_2_2_2
                </label>
              </li>
              <li>
                <input type="checkbox" name="level3" id="Grand_Child_2_2_2">
                <label class="Collapsable" for="Grand_Child_2_2_2">
                  <span></span> Grand_Child_2_2_2
                </label>
              </li>
            </ul>
          </li>
        </ul>
      </li>
      <li>
        <input type="checkbox" name="level1" id="Parent_3">
        <label class="Collapsable" for="Parent_3">
          <span></span> Parent_3
        </label>
        <ul>
          <li>
            <input type="checkbox" name="level2" id="Child_3_1">
            <label class="Collapsable" for="Child_3_1">
              <span></span> Child_3_1
            </label>
            <ul>
              <li>
                <input type="checkbox" name="level3" id="Grand_Child_3_1_1">
                <label class="Collapsable" for="Grand_Child_3_1_1">
                  <span></span> Grand_Child_3_1_1
                </label>
              </li>
              <li>
                <input type="checkbox" name="level3" id="Grand_Child_3_1_2">
                <label class="Collapsable" for="Grand_Child_3_1_2">
                  <span></span> Grand_Child_3_1_2
                </label>
              </li>
            </ul>
          </li>
          <li>
            <input type="checkbox" name="level2" id="Child_3_1">
            <label class="Collapsable" for="Child_3_1">
              <span></span> Child_3_1
            </label>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</div>

I am confused about why the checkbox behavior is not as expected. Is there something I'm overlooking?

Running the code in the snippet takes too long. For reference, here is the JSFIDDLE link: JSFIDDLE

Answer №1

Upon clicking a label, the associated checkbox won't check until after the label's click handler finishes its task. This means that while the label's function is running, the checkbox remains unchecked.

The solution is to attach the click handler to the checkboxes instead of the labels. However, the original code provided doesn't work correctly:

$(this).parent().children().toggle();
$(this).toggle();

This is because $(this) refers to the checkbox, not the label. Consequently, when you click on the label, it disappears. To fix this, modify the code as follows:

$(this).parent().children().toggle();
if ($(this).is(":checkbox")){
    $(`label[for=${this.id}]`).toggle();
} else {
    $(this).toggle();
}

By doing so, when you trigger toggle() from the checkbox click handler, it will toggle the corresponding label for that checkbox.

DEMO - Note that only the first two checkboxes have the Collapsable class used in the event binding, so clicking on the others won't result in any action.

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

When running grunt-bower, I am encountering an error stating that _.object is not a function

I am attempting to execute the grunt-bower task in order to copy all of my bower components. Encountered an error while running "bower:dev" (bower) task TypeError: _.object is not a function at Object.exports.getDests (/Users/wonoh/cocApp/node_modules/g ...

React Material-UI eliminates the 'content' property from the CSS pseudo-element

Creating a React MUI Box and styling it like this: <Box id='my-box' sx={{ '&::before': { content: 'Yay! ', backgroundColor: 'red' } }} >Life is beautiful</Box> However, duri ...

The combination of Asp.net and Bootstrap offers a powerful

I am facing an issue with using Bootstrap in my ASP.NET project. The page displays correctly on a desktop, but when I resize the page to mobile phone size, the navigation panel does not stay in dropdown position. Here is my code: <%@ Page Language="C ...

Create a dynamic animation effect by making a div slide on and off the screen

I'm having trouble figuring out how to make my div slide with a toggle button. I attempted to use variables, but since I have multiple instances of this, it's becoming too complicated to keep track of all the clicks on each one. $(document).r ...

How can I implement a AJAX GET request with a parameter in ASP.Net Core 2 Razor

Is there a way to send an AJAX GET request in my ASP.Net Core 2 Razor Application with a parameter that needs to be passed to the destination function? For instance, I have a Select field in my HTML. Depending on what value is selected, I want to retrieve ...

Leverage the power of jQuery and checkboxes to sort through posts

I have integrated the quicksand plugin into my WordPress theme to load posts from a selected category. Recently, I added custom taxonomies and field values to each post, and now I want to arrange my posts based on these criteria. As someone who is new to ...

The Stripe card element seems to be missing from the form

I'm a newcomer to angularjs and currently working on integrating version 3 of the stripe api into my angular application. I followed the steps provided on the stripe website, but faced an issue when trying to incorporate their code which is primarily ...

Verify and generate a notification if the value is null

Before saving, it is important to check for any null values and alert them. I have attempted to do so with the following code, but instead of alerting the null values, the data is being saved. . function fn_publish() { var SessionNames = getParamet ...

Having trouble accessing variable values within the nth-child selector in JavaScript

I am attempting to utilize the value of a variable within the element selector p:nth-child(0). Instead of hardcoding the number as 0, I want to dynamically assign the value of a variable. In this case, the variable is represented by i in a for loop. Howev ...

Firefox does not allow contenteditable elements to be edited if they are nested inside a parent element that is draggable

Here is a basic HTML example: <div draggable=true> <div contenteditable=true>can't edit me</div> </div> When testing in Chrome, I noticed that I was able to edit the contents of the contenteditable div, however, this functi ...

Convert the text inside a span element into a key-value object in JavaScript

How can I extract and save the text from a span element as key value pairs within a div? <div class="data-diff-span__composite-list-item__18c5zip data-diff-core__highlight-area__19c0zip"> <div class="data-diff-basic__class-row__4n ...

Customize the DOM with tailwind CSS in a Vanilla JavaScript project

I am attempting to hide the "mark as complete" button and replace it with a "completed" button by switching the classes from "hidden" to "completed" and vice versa. However, when I use an event listener to manipulate the DOM with the code provided below, t ...

Firefox failing to display CSS files on web pages

My project is deployed on IIS 7.5 and when trying to access it from a different machine using Firefox, all files are rendered except for the CSS files (although they work fine in IE). I have checked that the MIME type for .css files is correctly set up in ...

Unable to set the width for a div element within the bootstrap grid layout

When trying to set the width of a div tag to 100% within a bootstrap grid system (col-lg-3), I noticed that the div ends up taking the full width of the browser instead of just 100% of its parent(col-lg-3). .sidebar { color: #fff; f ...

Monaco Editor: Module 'monaco-editor' is missing despite being successfully installed

During the development of my desktop application with electron, I encountered an issue with installing Monaco Editor. After using npm install monaco-editor, running the application resulted in a message saying Cannot find module 'monaco-editor'. ...

Having trouble sending JSON data to the server using a POST request

I am encountering an issue while attempting to send JSON data to the server using the fetch API and PHP as the server-side language. The PHP code on the server side is quite simple: <?php header("Access-Control-Allow-Origin: *"); header("Access ...

Pondering the importance of the "zoom" feature in creating responsive designs

Currently, I am working on creating a responsive design using HTML and CSS. However, I have encountered an issue that I need help with: When resizing the window, the layout adapts perfectly. Similarly, when zooming in or out without resizing the window, e ...

index.html: using jquery for selecting colors

I attempted to integrate a jQuery plugin into my application, but it doesn't seem to be working. In the head section of my code, I have included: <link rel="stylesheet" media="screen" type="text/css" href="./style/colorpicker.css" /> <script ...

Tips for creating a reusable function in React.js?

I have a script that executes on input focus and passes certain values based on a specific logic. I would like to reuse this script for multiple input fields that trigger the focus event. How can I accomplish this? This is my current script: <input ...

Inline CSS alignment

While experimenting with layout inline elements, I came across some unusual behavior. Can someone please explain why there is a difference? I have applied the following CSS to both HTML structures: .time { position: relative; top:100px; heigh ...