Display or conceal information using several checkboxes

I need to hide an SVG graphic and display an icon using an invisible checkbox to handle the event. The problem arises when all checkboxes are selected upon firing the onchange event, causing all icons to appear and inputs to be selected.

Is there a way to set the event handler individually for each input[type="checkbox"]?

var $checkbox = $('.form-control'),
  $iconCheck = $('.check-circle'),
  $imgSVG = $('.img');

  $($checkbox).on('change', function() {
    if ($(this).is(':checked')) {
      $iconCheck.removeClass('d-none');
      $imgSVG.addClass('d-none');
    } else {
      $iconCheck.addClass('d-none');
      $imgSVG.removeClass('d-none');
    }
  });
img {
  display: block;
  width: 40px;
  height: 40px;
}
.d-none {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
  <figure>
    <img class="img" src="https://cdn3.iconfinder.com/data/icons/halloween-29/64/ghost-512.png" alt="">
    <i class="check-circle d-none">CHECKED!</i>
  </figure>
  <label for="checkboxTerror">Terror</label>
  <input id="checkboxTerror" type="checkbox" class="form-control">
</div>


<div class="card">
  <figure>
    <img class="img" src="http://icons.iconarchive.com/icons/icons8/ios7/256/Cinema-Comedy-2-icon.png" alt="">
    <i class="check-circle d-none">CHECKED!</i>
  </figure>
  <label for="checkboxTerror">Comedy</label>
  <input id="checkboxTerror" type="checkbox" class="form-control">
</div>

Screenshot Example

https://i.sstatic.net/Kerc9.png

Answer №1

My solution does not involve the use of Javascript

You can implement this using a clever CSS Trick.

/*var $checkbox = $('.form-control'),
  $iconCheck = $('.check-circle'),
  $imgSVG = $('.img');

  $($checkbox).on('change', function() {
    if ($(this).is(':checked')) {
      $(this).parent().children('.check-circle').removeClass('d-none');
      //$iconCheck.removeClass('d-none');
      $imgSVG.addClass('d-none');
    } else {
      $iconCheck.addClass('d-none');
      $imgSVG.removeClass('d-none');
    }
  });*/
img {
  display: block;
  width: 40px;
  height: 40px;
}
.d-none {
  display: none;
}
input[type=checkbox].form-control:checked + figure > img{
  display: none;
}
input[type=checkbox].form-control:checked + figure > .check-circle{
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
  <label for="checkboxTerror">Terror</label>
  <input id="checkboxTerror1" type="checkbox" class="form-control">
  <figure>
    <img class="img" src="https://cdn3.iconfinder.com/data/icons/halloween-29/64/ghost-512.png" alt="">
    <i class="check-circle d-none">CHECKED!</i>
  </figure>
  
</div>


<div class="card">
  <label for="checkboxTerror">Comedy</label>
  <input id="checkboxTerror2" type="checkbox" class="form-control">
  <figure>
    <img class="img" src="http://icons.iconarchive.com/icons/icons8/ios7/256/Cinema-Comedy-2-icon.png" alt="">
    <i class="check-circle d-none">CHECKED!</i>
  </figure>
   
</div>

Answer №2

Don't forget to define the variables $checkbox, $iconCheck, and $imgSVG outside of the $($checkbox).on('change', ...). If you don't, you'll end up selecting all elements instead of just those linked to the checkbox.

Instead, try using $('.form-control').each(...) and attaching a change event to each one individually. Then, you can locate the nearest image using $(this).parent().find('...').

This is an example that works:

$('.form-control').each(function() {
  $(this).on('change', function() {
    let $iconCheck = $(this).parent().find('.check-circle');
    let $imgSVG = $(this).parent().find('.img');

    if ($(this).is(':checked')) {
      $iconCheck.removeClass('d-none');
      $imgSVG.addClass('d-none');
    } else {
      $iconCheck.addClass('d-none');
      $imgSVG.removeClass('d-none');
    }
  });
});
img {
  display: block;
  width: 40px;
  height: 40px;
}

.d-none {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="card">
  <figure>
    <img class="img" src="https://cdn3.iconfinder.com/data/icons/halloween-29/64/ghost-512.png" alt="">
    <i class="check-circle d-none">CHECKED!</i>
  </figure>
  <label for="checkboxTerror">Terror</label>
  <input id="checkboxTerror" type="checkbox" class="form-control">
</div>


<div class="card">
  <figure>
    <img class="img" src="http://icons.iconarchive.com/icons/icons8/ios7/256/Cinema-Comedy-2-icon.png" alt="">
    <i class="check-circle d-none">CHECKED!</i>
  </figure>
  <label for="checkboxTerror">Comedy</label>
  <input id="checkboxTerror" type="checkbox" class="form-control">
</div>

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

431 - (Excessive Request Header Size)

First time asking for help, please take that into consideration What I've tried: I cleared my Google Chrome cache and cookies, attempted incognito mode, updated to the latest node version, but still encountering the same error. Error message in Chro ...

Scrolling in Jquery with offset for a fixed header

Currently, I am utilizing JQuery to create a smooth scrolling effect for images: function smoothScrollTo(hash) { $("html:not(:animated).,body:not(:animated)").animate({ scrollTop: $(hash).offset().top }, 650, function () { location ...

Tips for capturing a webpage thumbnail using a combination of jQuery and PHP from a specified link

Is there a way to capture a web page thumbnail using jQuery and PHP for a specific link? Imagine if I were to assign a PHP variable like this: $screen="http://www.yahoo.com" Can we implement the use of AJAX, jQuery, and PHP to display a thumbnail of the ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

What is the best way to incorporate Drift bot JS code into a static React NextJs application, such as a landing page?

I'm a beginner with ReactJS and I recently created a static website using ReactJS & NextJs. I decided to integrate a chatbot called 'Drift', but when following the installation instructions to insert JavaScript code in the <head> of HT ...

Reading a JSON file using Javascript (JQuery)

Struggling to figure out how to handle a JSON file using JavaScript. Here are the details : { "streetCity": { "132":"Abergement-Clemenciat", "133":"Abergement-de-Varey", "134":"Amareins" } } I am attempting to access ...

Code error: JSON unexpected token "&" encountered

When utilizing the $http.get() method for a GET request, the response is in JSON format, but some characters are HTML encoded. For example, the double quote " is encoded as &quot;. { &quot;description&quot;:&quot;invalid&quot;, ...

Set the background of the div element behind the image

I am trying to create a layout where the div color matches the size of an image behind it, with the image moving slightly on hover. Here is my code: <div class="row text-center about__gallery"> <div class="col-xs-12 col-sm-4"> <div cl ...

Is it a common occurrence for AJAX applications utilizing POST requests to encounter issues in Internet Explorer?

After some investigation, I have come across a bug in Internet Explorer that is causing intermittent failures for users running my application. This bug exists within the HTTP stack of IE and impacts all applications utilizing POST requests from this brows ...

Calendar display - Days grouped on the left side, with the times arranged across the top in week view?

I'm curious whether it's feasible to display a comprehensive calendar view featuring the days on the left side for the week and the times across the top. Can such a layout be achieved? https://i.sstatic.net/SFtmG.png ...

Filtering array objects based on elements in another array

I am trying to filter out elements from one array based on matching ids in another array. My first array looks like: const toFilter = [1,4,5] And the second array has a structure similar to this: const foo = [{id: 1, time:XXX}, {id:2, time:XXX}, {id: 3, t ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...

Submitting a form with Multer when the user chooses to upload a file or not

I have integrated multer into my express app for handling form submissions. The issue I am facing is with the optional image upload feature in the form. Users have the choice to add a photo if they want, but they should also be able to submit the form wi ...

Utilizing the onclick attribute in combination with a partial HTML button

When utilizing the onclick attribute in the HTML markup without using a partial tag, the onclick function is functional. However, when the exact same markup is used within a partial, the onclick function fails to execute. Query: Is there a method to make ...

How can I get my view to render in node.js/express using XMLHttpRequest()?

After working on my node/express app for the past three days, I am still facing an issue with making a GET request to a specific route from the client side. Despite using XMLHttpRequest and setting the necessary headers for authorization, the app remains s ...

Comparison: Chrome extension - utilizing default pop-up vs injecting a div directly into the page

I find myself perplexed by the common practices used in popular Chrome extensions. I am currently working on creating my own Chrome extension and after completing a basic tutorial, I have set up a default popup page that appears when clicking the extensi ...

Sorting images can be quite a challenge

Struggling to organize images with jQuery. Reviewed http://jqueryui.com/demos/sortable/#display-grid, and it's functional. The issue arises when sorting images left to right, causing the form to shift left (but not vice versa). Despite adjusting margi ...

Issue with filtering tasks in a Task Tracker application

Hey there! I'm new to JavaScript and I've been working on a todo app. Everything seems to be running smoothly except for the filter function, which I just can't seem to get working no matter what I try. I previously had a similar app with ma ...

Can the color of a highchart graph be altered simply by clicking on the line?

Greetings! I am currently working on plotting a graph using highchart and I was wondering if there is a way to allow users to change the color of the plotted line by simply clicking on it and selecting a color from a color picker tool. I do not want to lim ...

Notifying a Child Component in React When a Props-Using Function Resolves a REST Call

When I submit an item or problem, I trigger a function in the parent component that has been passed down to the child component as props. After sending my information, I want to clear the input fields. The issue is that I am clearing the input fields immed ...