Is there a way to toggle checkboxes by clicking on a link?

To toggle the checkboxes within a specific section when a link is clicked within that section, I need to ensure the script functions correctly. The checkboxes and the button must be nested within the same parent element. The HTML markup is provided below.

<div class="parent">

<div class="child">

    <a class="filter-check-btn">button</a>

    <div class="all-checkboxes">
        <div class="sep-chk">
            <label class="rad">
                <input class="filter-chk-box" type="checkbox" checked> Checkbox
            </label>
        </div>
        <div class="sep-chk">
            <label class="rad">
                <input class="filter-chk-box" type="checkbox" checked> Checkbox
            </label>
        </div>
    </div>

</div>

<div class="child">

    <div class="all-checkboxes">
        <div class="sep-chk">
            <label class="rad">
                <input class="filter-chk-box" type="checkbox" checked> Checkbox
            </label>
        </div>
        <div class="sep-chk">
            <label class="rad">
                <input class="filter-chk-box" type="checkbox" checked> Checkbox
            </label>
        </div>
        <div class="sep-chk">
            <label class="rad">
                <input class="filter-chk-box" type="checkbox" checked> Checkbox
            </label>
        </div>
    </div>

</div>
</div>

Below is the script:

$(".filter-check-btn").on('click', function() {
    $(this).toggleClass('active');
    $(this).parent().parent().children(".filter-chk-box").prop('checked', false);
});

$(".filter-check-btn.active").on('click', function() {
    $(this).toggleClass('active');
    $(this).parent().parent().children(".filter-chk-box").prop('checked', true);
});

Answer №1

To update your jQuery script, use the following code snippet:

$(".filter-check-btn").on('click', function() {
    $(this).toggleClass('active');
    if ($(this).hasClass("active"))
    $(this).parent().parent().find(".filter-chk-box").prop('checked', true);
    else
    $(this).parent().parent().find(".filter-chk-box").prop('checked', false);
});

Check out the updated code on Fiddle.

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

What is the best way to pass information between Express middleware and endpoints?

Many middleware packages come with factories that accept an options object, which often includes a function to provide necessary information to the middleware. One example of this is express-preconditions: app.use(preconditions({ stateAsync: async (re ...

Numpad functionality in JQuery malfunctioning post-ajax request

Using the jQuery numpad plugin has been flawless until after an AJAX call. I have tried various functions like on('click') and others, but unfortunately, none of them worked as expected. Apologies for my poor English! You can find the extension l ...

Loading Textures in Three.js Using async / await is the Way to Go

Recently, I took a Drawing class and learned about creating objects: export class Drawing { constructor(texture) { const material = new MeshBasicMaterial({ color: 0xffffff, map: texture }); this.m ...

Issue encountered with the style parameter in print-js when attempting to print from a Vue.js component

While browsing the print-js documentation, I came across a feature that allows us to pass style as a string to the printJS function. However, when attempting to apply this style, I encountered an error preventing the print action: The error I'm facin ...

Communicate through PHP and JavaScript chat to display HTML content in the chat window

I have been attempting to display HTML output in the chat window but instead, it is showing the HTML code. Here are the two files involved in the chat system: chat.js `function chatHeartbeat(){ var itemsfound = 0; if (windowFocus == false) { var ...

Accessing nested arrays and objects within JSON using Node.js

I'm in the process of developing an application that retrieves a JSON response from an API call using SONARQUBE. With node js, how can I extract the value of duplicated_lines from the following JSON object? I attempted the code below but it always r ...

What is a clear indication that a <div> is filled with text?

Picture a scenario where a website contains an element that needs to be filled with random text using JavaScript. Once the div is completely filled, it should reset and begin again. It may sound odd, but the question is: how will the JavaScript determine w ...

Experiencing a lack of defined or no outcome when outputting the API callback

I am troubleshooting an issue with my script that searches for movie titles from a database. While I receive results in the console without any errors, the renderMovies function is not storing the API movie title, plot, and other details properly in my var ...

A guide on initiating a get request with URL in React

Utilizing React for the frontend and express for the backend has been my approach. By defining get methods in my express like this:- app.get('/addBill',(req,res)=>{ // --first method res.render("addBill"); }); app.get(&a ...

Refreshing the page to display new data after clicking the update button

function update(){ var name= document.getElementById("TextBox").value; $.ajax({ url: '....', type: 'post', ...

Collecting information from form submissions, accessing data from the database, and displaying the results

I am currently working on a project using nodejs, express, and mongodb within the cloud9 IDE. My goal is to create a page with a form that allows users to input data, search for corresponding information in the database, and display that data on the same ...

Incorporating a transparent icon onto an HTML background

I'm struggling to place a transparent white envelope icon on a green background. I don't understand why it's not working, especially when the telephone icon worked fine. Side Question.: Any recommendations for how to add something above the ...

Unable to perform the GET request method due to data indicating [object object]

Currently, I am attempting to use a get request method within both Vue and Express in order to retrieve data based on my v-model. Displayed below is the code where I am trying to send the data to Express. getResult() { axios .get( `${process. ...

What is the method to close the picker when using type="datetime-local"?

Currently, I am utilizing Vue with the "datetime-local" type for input. While I can successfully select the date and time, my goal is to have the picker close automatically after a selection has been made. I've experimented with adding an onchange ev ...

Is there a jQuery alternative to the collect and map functions in Prototype?

Is there a similar iterator function in jQuery that functions like "collect" and "map" in Prototype? These functions provide the result of applying an iterator to each element: Appreciate the help! ...

Send the output of an asynchronous ajax request to the designated function within the jQuery Validation plugin

Utilizing the jQuery Validation plugin (JVP) for server-side validations via ajax has been seamless, except for one hitch: JVP struggles with performing remote validation on blank fields. While it's easy to use its default required: true rule for sim ...

Issue Encountered: Problem with Implementing Google Fonts in WordPress Theme

I am currently facing an issue with a function in my Wordpress theme's functions file that is supposed to add Google Fonts to the theme. However, I keep receiving the following error message: Parse error: syntax error, unexpected '=', expec ...

Utilizing highlight.js for seamless integration with vue2-editor (Quill)

I am having trouble connecting vue2-editor (based on quill) with highlight.js Despite my efforts, I keep encountering an error message that reads: Syntax module requires highlight.js. Please include the library on the page before Quill. I am using nu ...

What is the best way to create divs that can close and hide themselves when clicked from inside the div itself?

I have a situation in my code where clicking a link reveals a div, and then the same link must be clicked again to hide it. However, I want to modify this so that any link within the div can also hide it when clicked. I currently have eight divs set up lik ...

The positioning of images on the fabricjs canvas seems to be unreliable and inconsistent

When trying to place a series of 4 images at specified coordinates in fabricjs, I am facing inconsistencies with their placement upon page load. Refreshing the page usually resolves the issue, but I want to prevent this from happening altogether. If anyon ...