Checkboxes with the ability to hide and show multiple options

Just dipping my toes into jQuery, so bear with me...

I have 3 checkboxes and I'm trying to hide a specific tag if one of the checkboxes is checked. But, I want all the other tags to become visible if they are not checked. Additionally, if 2 checkboxes are checked, I need to hide all associated tags.

I hope this explanation makes sense, and any assistance is greatly appreciated!

Thank you in advance

<input type="checkbox" class="example" id="check1"><label>check1</label>
<input type="checkbox" class="example" id="check2"><label>check2</label>
<input type="checkbox" class="example" id="check3"><label>check3</label>

<a class="check1" href="">check1</a>
<a class="check2" href="">check2</a>
<a class="check3" href="">check3</a>

<a class="check1" href="">check1</a>
<a class="check2" href="">check2</a>
<a class="check3" href="">check3</a>

<a class="check1" href="">check1</a>
<a class="check2" href="">check2</a>
<a class="check3" href="">check3</a>



    .hide {
      display: none;
    }



    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>

    <script>
      $('#check1').change(function() {
        if ($(this).is(":checked")) {
          $(".check1").addClass("hide");
        } else {
          $(".check1").removeClass("hide");
        }
      });
    </script>

Answer №1

Implement the toggle() function

$('.sample[type=checkbox]').change(function() {  
    $("."+this.id).toggle(!this.checked);
});

Live Demo

Answer №2

To make it work properly, follow these steps:

  1. Generalize the checkboxes by binding to the .example class.
  2. Retrieve the ID dynamically from the clicked checkbox.
  3. Wrap everything within the $(document).ready() function.
  4. Put the <input /> and label text inside the <label> tag!

The HTML has been updated for better appearance and semantics.

Updated Code Snippet:

$(function () {
  $('.example').change(function() {
    theID = this.id;
    if ($(this).is(":checked")) {
      $("." + theID).addClass("hide");
    } else {
      $("." + theID).removeClass("hide");
    }
  });

  // Check on page load.
  $(".example").each(function () {
    if ($(this).is(":checked"))
      $("." + this.id).addClass("hide");
  });
  
});
.hide {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<div>
  <label><input type="checkbox" class="example" id="check1">check1</label>
  <label><input type="checkbox" class="example" id="check2" checked>check2</label>
  <label><input type="checkbox" class="example" id="check3">check3</label>
</div>

<div>
  <a class="check1" href="">check1</a>
  <a class="check2" href="">check2</a>
  <a class="check3" href="">check3</a>
</div>

<div>
  <a class="check1" href="">check1</a>
  <a class="check2" href="">check2</a>
  <a class="check3" href="">check3</a>
</div>

<div>
  <a class="check1" href="">check1</a>
  <a class="check2" href="">check2</a>
  <a class="check3" href="">check3</a>
</div>

Answer №3

Here is an example of jQuery code that you can use to toggle classes based on checkbox changes:

$('input[type="checkbox"]').change(function () {
    var checkboxId = $(this).attr("id");
    if ($(this).is(":checked")) {
        $("." + checkboxId).addClass("hide");
    } else {
        $("." + checkboxId).removeClass("hide");
    }
});

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

Troubleshooting "Module Not Found" issue with Vue.js single page component integrating Google Maps

I'm facing an issue while trying to integrate a Google Map from the Google Maps API into my Vue.js application. I have obtained my API key and made an attempt to display the map. However, upon running the app, Atom throws a "Module not found" error me ...

Refreshing the current page within a Vue single-page application website

I've attempted numerous methods to resolve this issue. I have tried using .htaccess in an Apache hosting environment (which is my preferred setup for hosting my site), Heroku, and Netlify with both a _redirects file and netlify.toml file. Unfortunatel ...

Challenge of integrating React Router with Express GET requests

I am struggling to understand how react router and express routes work together. This is what I currently have set up: app.get('*', function(req, res) { res.sendFile(path.resolve(__dirname) + '/server/static/index.html'); }); // ...

Retrieving the JSTree JSON data along with its associated metadata

We've implemented jstree as a tool for editing our navigation menu, and have been adding metadata to the tree nodes in this manner: var data = currentNode.data("jstree"); data.title = textBoxTitle.val(); data.linkType = textBoxLink.val(); Although I ...

Issue with PrimeFaces radiobutton styles not updating after being clicked programmatically

My setup includes a p:selectOneRadio constructed like this: <p:selectOneRadio id="positionRadio" value="#{employeeBean.empPosition}" converter="#{empPositionConverter}" layout="custom" required="true" requiredMessage="Please select ...

How to create a greyed-out background with Angular Material's MatSpinner

I am currently working on implementing a loader component with the ability to show or hide based on a boolean value in the component's HTML. I have successfully included a matSpinner element, but when embedded in app.component.html, the background doe ...

Steps to make a div resize based on the inner element's dimensions

I am currently working on a parent div called "like_user_wrapper" that contains a small image icon. Below is the snippet of my code: <?php echo '<div class="like_user_wrapper" id="'.$post_id.'like_user_wrapper">'; $who_li ...

One feature in jQuery that allows for the dynamic generation of multiple elements within a single class

After searching through previous questions, I was unable to find the answer. Here is the dynamically generated HTML: <a class="finddiv" id="#div_0">date1</a> <a class="finddiv" id="#div_1">date1</a> <a class="finddiv" id="#div_ ...

The POST function in jQuery often returns the [Object object] result

Looking to extract a string from a PHP file using jQuery's post method. function getString(string) { return $.ajax({ type: 'POST', url: 'scripts/getstring.php', data: { 'string': string } ...

Leveraging the `app.get()` method in Firebase cloud functions to retrieve and interact with files

I am currently integrating Firebase Hosting with Firebase Functions to restrict access to .html content only to users with a valid Firebase token. Within my iOS app, I can successfully send the token when accessing Firebase Hosting. The Cloud Function dec ...

Fixing Firebase and React errors in JavaScript functions

Thank you for your understanding. I am currently integrating Firebase into my website. However, when I invoke the signup function in FormUp.js (which is declared in AuthContext.js), it does not reference the function definition. As a result, the function c ...

When a map is assigned to object.children[0] in Three.js, it affects the entire object's map

In my attempt to assign a map to every object loaded with OBJLoader in an obj file, I encountered a problem. When trying to assign a different map to only one object from the file while keeping the rest with the previous map, the map changes for every obje ...

Creating a Blog Post with Pagination on Blogger

After creating pagination for 1 to 10 posts, I encountered an issue where clicking on page 1 or 2 does not show as the visited or active page. Any advice on how to fix this? Below is the CSS code: .post-pagination { margin: 100px auto; text-align ...

Examining the appearance of react-hot-toast using jest testing

As I work on my application, I am facing a challenge in writing a test for the appearance of a react-hot-toast. Whenever a specific button is clicked, this toast pops up on the screen and disappears after a brief moment. Despite being visible both on the s ...

Is it possible to generate a PagedListPager without the need to invoke a function?

Managing a list with ajax calls has been fairly smooth on the initial load. The search button triggers an ajax call that loads the first page of results without issues. However, an obstacle arises when trying to implement PagedListPager which ends up reset ...

What is the best way to change the text within the first tag of an HTML markup using either jQuery or basic JavaScript?

My task involves dealing with an array of markup strings, similar to: const items = [ '<p class="item">text</p>', '<h1>hello</h1>', ]; I am looking for a way to replace the text content within the ...

Unlocking your phone with a smooth Jquery scroll animation

https://i.sstatic.net/TpwoPPnJ.gif Is there a way to create an onscroll unlock screen animation where the phone remains static/sticky for a period before moving on scroll? I also want to include a parallax effect with text alongside it. I've impleme ...

Tips for preventing errors in JavaScript date formatting

Currently, I am utilizing the DHTMLX Scheduler within my web application and aiming to access data for each event. Fortunately, I discovered a method to achieve this using scheduler._events which provides the following information: 1581498064943: {…} ​ ...

The :not() selector in CSS3 seems to be ineffective on sibling elements

In my simple design, I have specified that text should appear in red unless it is within a footer element. This style is applied successfully to p tags, a tags, and others. However, for some reason, the styling does not work when I target the footer tag. ...

Is it possible to utilize template literals for defining function names in Javascript?

Is it possible to use template literals for dynamically naming functions? let variable = "something" function `constant${variable}` () { //perform a task } ...