How to toggle the visibility of checkboxes in JavaScript based on their checked status

I am facing an issue with some checkboxes as I am unable to filter them based on whether they are checked or not.

The concept is simple. When I click on "All", all the checkboxes should be displayed. However, when I click on "Selected", only the selected checkboxes should be visible while the unchecked ones should be hidden.

Below is a code snippet that needs updating in your response to demonstrate how this can be achieved:

Thank you!

//array of options
var choices = new Array();
choices[0] = "January";
...
...
* {
    box-sizing: border-box;
}
#data {
padding:5px;
width:100vw;
}

...
...
...
<span onclick="">All</span> | <span onclick="">Selected</span>
...
...
...

Answer №1

There are two functions that can help achieve this task. The first function displays all the parent elements of the input fields, while the second function hides the parent elements of inputs that are not checked.

function DisplayAllParents() {
  $("input").parent().show();
}

function HideUncheckedParents() {
  $("input:not(:checked)").parent().hide();
}

//array of options
var choices = new Array();
choices[0] = "January";
choices[1] = "February";
choices[2] = "March";
choices[3] = "April";
choices[4] = "May";
choices[5] = "Juny";
choices[6] = "July";
choices[7] = "August";
choices[8] = "September";
choices[9] = "October";
choices[10] = "November";
choices[11] = "December";

var target = new Array()
target[0] = "5";
target[1] = "8";

var cbh = document.getElementById('checkboxes');
var val = '';
var cap = "";

var j = "";
var t = document.getElementById('t');

// the loop is creating the checkboxes with name, value...
for (var i in choices) {
  //Name of checkboxes are their number so I convert the i into a string.
  j = i.toString();

  val = j;
  //cap will be the value/text of choices[i]
    var cb = document.createElement('input');
    var label = document.createElement("label");

    cap = choices[i];
    var text = document.createTextNode(cap);
    cb.type = 'checkbox';
    cbh.appendChild(cb);
    cb.name = cap;
    cb.value = val;
    label.appendChild(cb);
    label.appendChild(text);
    cbh.appendChild(label);
    cb.addEventListener('click', updateText)
    if (target.indexOf(i) >= 0) {
      cb.checked = true;
    }
}

updateText();

function updateText() {
  t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
}

function DisplayAllParents() {
  $("input").parent().show();
}

function HideUncheckedParents() {
  $("input:not(:checked)").parent().hide();
}
* {
box-sizing: border-box;
}

#data {
padding: 5px;
width: 100vw;
}

.multiselect {
overflow: visible;
padding: 0;
padding-left: 1px;
border: none;
background-color: #eee;
width: 100vw;
white-space: normal;
height: 200px;
}

.checkboxes {
height: 100px;
width: 100px;
border: 1px solid #000;
background-color: white;
margin-left: -1px;
display: inline-block;
}

label {
display: inline-block;
border: 1px grey solid;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span onclick="DisplayAllParents()" style="cursor:pointer">All</span> | <span onclick="HideUncheckedParents()" style="cursor:pointer">Selected</span>
<form>
  <div id="data">
    <div class="multiselect">
     <div id="c_b">
       <div id="checkboxes">
        </div>
      </div>
    </div>
  </div>
</form>
<textarea id="t"></textarea>

Answer №2

To display or hide the parent element of checked elements, you can use the following code snippet with jQuery:

  $("#chkAll").click(function(){
    $(":checkbox").parent().show();
  });

  $("#chkSelected").click(function(){
    $(":checkbox").parent().hide();
    $(":checked").parent().show();
  });

Check out the updated snippet below:

$(document).ready(function(){
  //array of options
  var choices = new Array();
  choices[0] = "January";
  choices[1] = "February";
  choices[2] = "March";
  choices[3] = "April";
  choices[4] = "May";
  choices[5] = "Juny";
  choices[6] = "July";
  choices[7] = "August";
  choices[8] = "September";
  choices[9] = "October";
  choices[10] = "November";
  choices[11] = "December";

  var target = new Array()
  target[0] = "5";
  target[1] = "8";

  var cbh = document.getElementById('checkboxes');
  var val = '';
  var cap = "";

  var j = "";
  var t = document.getElementById('t');

  // the loop is creating the checkboxes with name, value...
  for (var i in choices) {
    //Name of checkboxes are their number so I convert the i into a string. 
    j = i.toString();

    val = j;
    //cap will be the value/text of choices[i]
    var cb = document.createElement('input');
    var label = document.createElement("label");

    cap = choices[i];
    var text = document.createTextNode(cap);
    cb.type = 'checkbox';
    cbh.appendChild(cb);
    cb.name = cap;
    cb.value = val;
    label.appendChild(cb);
    label.appendChild(text);
    cbh.appendChild(label);
    cb.addEventListener('click', updateText)
    if(target.indexOf(i)>=0){
      cb.checked =true ;
    }

  }
  updateText();
  function updateText() {
    t.value = [null, ...document.querySelectorAll('#checkboxes [type="checkbox"]')].reduce((s, el) => el && el.checked ? s = (s || '') + el.value + '$#' : s || '')
  }

  $("#chkAll").click(function(){
    $(":checkbox").parent().show();
  });

  $("#chkSelected").click(function(){
    $(":checkbox").parent().hide();
    $(":checked").parent().show();
  });
});
* {
    box-sizing: border-box;
}
#data {
    padding:5px;
width:100vw;
}
.multiselect {
overflow: visible;
padding:0;
padding-left:1px;
border:none;
background-color:#eee;
width:100vw;
white-space: normal;
height:200px;
}
.checkboxes {
height:100px;
width:100px;
border:1px solid #000;
background-color:white;
margin-left:-1px;
display:inline-block;
}
      
            label {
display: inline-block;
border: 1px grey solid;
padding:5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="chkAll">All</span> | <span id="chkSelected">Selected</span>
<form>
<div id="data">
<div class="multiselect">
<div id="c_b">
<div id="checkboxes">
</div>
</div>
</div>
</div>
</form>
<textarea id="t"></textarea>

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

Error: SvelteKit server-side rendering encountered a TypeError when trying to fetch data. Unfortunately, Express is not providing a clear TypeScript stack trace

I've been monitoring the logs of the SvelteKit SSR server using adapter-node. After customizing the server.js to utilize Express instead of Polka, I noticed some errors occurring, particularly when the fetch() function attempts to retrieve data from ...

Slide the first div upward to display the text in the second div when hovering over the first div

I'm facing an issue where a div needs to move upwards when hovering over it. To see an example, take a look at this JSfiddle. The desired outcome is as follows: As illustrated, the right div is the one being hovered. I have attempted to create this ...

Implement Icon using CSS Class in jQuery Mobile

Is there a way to use an icon in jQuery Mobile on a span element and also support retina display without giving the span a fixed width? Should I attempt to utilize Media Queries to achieve this, or is there an "official way" to do it? Thanks, Nils ...

Setting up craco for jsx in your project

I am currently utilizing craco and grappling with how to configure jsx. I keep encountering the error below: Support for the experimental syntax 'jsx' isn't currently enabled (4:17): The suggestion is to add `babel/preset-react or utilize ...

Waiting for onAuthStateChanged in Supabase to prevent flickering when using useEffect: What's the right way to ensure the request has finished?

I have successfully implemented authentication and even included a loading state to display a loader until the state changes. However, I am experiencing flickering upon reload, which only seems to happen with Supabase. Previously, when using the Firebase v ...

Restore font-weight if a different list item is chosen

I previously inquired about setting the font-weight to bold on a text element when selected. Thanks to @Eric, this has been successfully implemented! However, I am facing an issue where clicking on one text makes it bold, and then clicking on another text ...

problem with overlapping elements

Hey there! I'm facing a CSS issue where an error message appears below the contact us box if the user doesn't fill the text box properly. However, there's an overlap issue with the image below the contact us box. Any suggestions on how to s ...

Ag-Grid: A Guide to Storing and Restoring Columns with Filter Settings

Ag-Grid allows us to easily filter columns. One requirement I have is to save the column filter order in a SQL database backend. I have implemented a method for saving the column order, but it doesn't seem to work properly. onGridReady: function(par ...

Can I compile a build using browserify/babel for a specific browser version?

After reviewing compatibility tables, like the one found at , it appears that Chrome is on the verge of fully supporting ES6. This leads me to believe that I can omit certain elements during development. var babelifyOptions = { presets: ['es2015& ...

Searching for an element with line breaks in its class name on a website using Selenium in Python

I am attempting to extract information from LinkedIn, however I have noticed that the element IDs change every time I refresh the page using Selenium. As a result, I attempted to use class names to locate all elements, but the class names contain newline c ...

Center the input field both vertically and horizontally within an overlay

When the user clicks on the search icon, I want to display the search field as an overlay. Currently, the overlay is working but the search input field is appearing in the middle vertically. Check out the Fiddle <a href="#overlay" id="open-overlay"&g ...

Application in Ionic for streaming YouTube videos

I am facing an issue with my Ionic app that is deployed as a web app. The problem arises when displaying YouTube videos on different screen sizes. While the video fits perfectly on small screens and scrolling is smooth, it becomes problematic on larger des ...

The latest alpha version of Angular2 Material Design (alpha.9-3) encountered a "404 not found" error when trying to access @angular

After carefully following the steps outlined in the angular material2 Getting Started guide to install @angular/material, I made updates to package.json, app.module, and systemjs.config using Atom. Specifically, I added the line '@angular/material&apo ...

Clicking on the button will advance to the next tab rather than selecting the tab

I have this code snippet in HTML: $(document).ready(function() { $("div.bhoechie-tab-menu>div.list-group>a").click(function(e) { e.preventDefault(); $(this).siblings('a.active').removeClass("active"); $(th ...

How to iterate over the request body in Node.js using Express?

When I send a request with data in the form of an array of objects: [ {id: "1"}, {id: "2"}, {id: "3"} ] I am utilizing JSON.stringify() and my req.body ends up looking like this: { '{"id":"1"} ...

What is the best way to achieve rounded table borders without duplicating them or relying on border-collapse?

After discovering a helpful Stack Overflow answer regarding rounding table corners, I attempted to implement the provided CSS code: /* table { border-collapse: collapse; }*/ table, tr, td, th{ border: 1px solid; text-align: center; /*paddin ...

Generating a dynamic list of items using arrays in JQuery

I need help creating ul > li elements dynamically using jquery. Here is the data I have: var nodeDataArray = [{ key: 0, name: "George V" }, { key: 1, parent: 0, name: "Edward VIII" }, { key: 2, parent: 0, name: "George ...

What is the best way to implement a 2-dimensional array in Django's template using jQuery?

I have a 2d array called "pre" in views.py. I passed this array to template.html and now I want to utilize the values from the second column of each row in the pre array as the initial values for text boxes. Below is the script: The variable i.toString() ...

Display text with a hover effect

When I hover over an image, I want to display some text. I managed to make it work, but the text was expanding the size of the card. To solve this issue, I added a display none to the text class. I can't include all the code here, so here's a sn ...

Troubleshooting: Issue with Adobe Analytics DTM custom script property not being successfully

I'm attempting to display the most recent time I made changes and the current version of the library. Initially, I crafted a data element called Global - Example: return "DTM:" + _satellite.publishDate.split(" ")[0] + "|" + "Adobe:" + s.version; Su ...