Verify whether a checkbox is selected and then add a specific style to the parent element using jQuery

Here is a list with checkboxes:

<ul class="cate_select_ul">
    <li>
        <!-- outer checkbox A -->
        <label><input value="251" type="checkbox" name="post_category[]">Automobiles &amp; Transport</label>
        <ul class="children">
            <li>
                <!-- inner checkbox A -->
                <label><input value="252" type="checkbox" name="post_category[]">Car Parts</label>
            </li>
        </ul>
    </li>
    <li>
        <!-- outer checkbox B -->
        <label><input value="251" type="checkbox" name="post_category[]">Automobiles &amp; Transport</label>
        <ul class="children">
            <li>
                <!-- inner checkbox B -->
                <label><input value="252" type="checkbox" name="post_category[]">Car Parts</label>
            </li>
        </ul>
    </li>

</ul>

I am looking to determine if the inner checkbox is checked, and if so, change the style of the label around the parent outer checkbox. I attempted the following code but it's not working correctly:

if($('ul.children input[name="post_category[]"]:checked').length > 0){
$("this").parent().parent().parent().parent().children("label").css({"color":"red"});
}

Any suggestions on how to achieve this desired effect?

Answer №1

The reason why your example is not functioning is because the $("this") statement is trying to select an element with a tag type of <this>, which does not exist, resulting in nothing being selected.

Typically, $("this") should be $(this) (as this is a keyword and not a string). However, in your scenario, it seems that there is no specific scope, causing the variable this to possibly refer to the window object. You can confirm this by using console.log(this).


To resolve this issue, you can iterate over the elements using the .each() method so that this points to the current selected input element. Additionally, instead of chaining the .parent() method four times, you can utilize the .closest() method to target the nearest ancestor:

Check out this Example

$('ul.children input[name="post_category[]"]:checked').each(function() {
  $(this).closest('.children').prev('label').css('color', '#f00');
});

In addition, you can directly select the elements without having to use the .each() method:

Below, the :has() selector is used to target ul.children elements with checked descendant input[name="post_category[]"] elements. Subsequently, the preceding label element is chosen for CSS alteration:

View Example Here

$('ul.children:has(input[name="post_category[]"]:checked)').prev('label').css('color', '#f00');

For those interested in incorporating this into a change event listener, the implementation would resemble:

Updated Example

$('ul.children input[name="post_category[]"]').on('change', function() {
  $(this).closest('.children').prev('label').toggleClass('selected', this.checked);
});

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 displaying sub links when hovering over a link

My code can be found at http://jsfiddle.net/ChvjL/4/ I need the sub links link1a, link1b, link1c to appear when the mouse pointer is over Link1. The same functionality should apply for Link2 as well. If anyone can assist me in solving this issue, I woul ...

Cursor hovers over button, positioned perfectly in the center

I am facing a challenge with implementing a hover function for a set of buttons on the screen. The goal is to display the mouse pointer at the center of the button upon hovering, rather than the actual position of the cursor being displayed. I have tried u ...

The justify-content-center class in the latest version of Bootstrap (v4.5) appears to be malfunction

I'm currently working on creating a responsive contact section for a website I'm developing for a small local company. Unfortunately, the icons in their container are not being centered despite using the justify-content-center class from Bootstra ...

Seeking a precise placement, must find a CSS-only answer

After spending two days experimenting with different CSS styles like absolute positioning, inline/inline-block display, and flex display, I have yet to find a solution for styling a timestamp's label position using pure CSS. https://i.stack.imgur.com ...

Alter the dimensions and material displayed on Vue

In my Vue.js project, I have a topbar with two divs whose size and content need to be adjusted based on whether the user is logged in. If they are not logged in, it should look like this: <div id='search' width="400px"></div><div ...

Navigate to a different web page within the body tag without changing the current URL by utilizing a hash symbol

I am working with two HTML files, index.html and about.html. My goal is to display the content of about.html within my index.html without navigating away from it. After observing many websites, I noticed that they often use #about in their URLs to dynamic ...

Breaking down and analyzing XML information

I have data that I need to retrieve from an XML file, split the result, parse it, and display it in an HTML element. Here is a snippet of the XML file: <Root> <Foo> <Bar> <BarType>Green</BarType> &l ...

Uncertain about the ins and outs of AJAX

I am a complete beginner in web development. Although I have studied JavaScript and HTML through books, my understanding is still limited. I have never worked with AJAX before and find most online examples too complex for me to follow. My goal is to crea ...

Merging the HTML and JQuery scripts to create a unified webpage

My Website Dilemma: Working with Intuit Web Designs has presented me with a unique challenge in terms of HTML setup. The platform requires me to paste anything within the <head></head> tags in a separate box, rather than directly into the main ...

Guide on populating a series of rectangles in a line based on values stored in an array using d3.js

I have 100 rectangles arranged in a 10x10 square. My goal is to assign colors to the rectangles based on values from an array var avg = [1, 4, 4, 7, 11, 15, 58] I'm facing an issue at the value 4 being repeated and I find the current code quite mess ...

CSS - Placeholder styling not being effective when selectors are grouped

Why is Chrome successful at executing this code: .amsearch-input::-webkit-input-placeholder { color: red; } <input class="amsearch-input" placeholder="It works!" /> ...while it doesn't work in other browsers: .amsearch-input::-we ...

Ways to modify textbox background shading when an error arises

I have a text box where I input an email address. If the email is in the wrong format, I want the background color of the text box to change. This is the jQuery code I have written: $(function() { $(':text').hover(function () { this ...

What is the most effective way to create these lines using CSS?

Is there a way to create the background image shown in the link below? https://i.sstatic.net/YB4N7.png ...

What is the reason behind the necessity of having content inside div tags in order for the style to take effect

Upon analyzing the code provided, it was observed that if there is no content inserted between the tags as shown in <div id="header"></div, the corresponding style does not get applied. Is it mandatory to always have content placed between the t ...

Modify the color of CSS for all elements except those contained within a specific parent using jQuery

I have a color picker that triggers the following jQuery script: //event.color.toHex() = hex color code $('#iframe-screen').contents().find('body a').css('color', event.color.toHex()); This script will change the color of al ...

Enhance User Experience in IE11 by Providing Font Size Customization with Angular (Using CSS Variables)

I am in the process of developing an Angular application. One of the requirements is to allow the user to choose between small, medium, or large font sizes (with medium being the default) and adjust the font size across the entire webpage accordingly. Wh ...

How can I use absolute positioning and scrolling with an Iframe?

One of the key elements of this website is the implementation of iframes, with only one displayed at a time. However, my current issue revolves around the inability to scroll within these iframes due to their absolute positioning. I have attempted variou ...

The HTML footer designed with bootstrap is not behaving as expected. It is not staying fixed at the bottom of the page and is not displaying at full width despite my coding efforts

Working on a small Sinatra app with bootstrap for layout, I'm encountering some issues. The layout is not sticking to the bottom and not displaying at 100% width as intended. Additionally, the footer text is not centering even after applying the text ...

What is the best technique to position a div at the bottom of a container that has a height of 100

After many attempts and searching for answers, I'm still struggling to figure out how to make the div float to the bottom with 100% height. I've even considered if it's an issue with Pure or something else entirely. It's definitely frus ...

Adjusting the size of an image to fit within a canvas in relation to the width

I have a canvas with an image inside, measuring 800 pixels in width and 520 pixels in height. How can I properly scale the image drawn on the canvas to fit any browser size while maintaining its correct aspect ratio? Thank you! ...