Looking to eliminate the unchecked checkbox value from the list using jQuery?

After selecting a checkbox, the text/value is displayed in an li element. However, if I uncheck the first box and check the second one, I want to remove the text/value associated with the first checkbox as shown below:

View Image Here

Here is my code snippet:

$('input[type="checkbox"]').bind('change', function() {
    var alsoInterested = '';
    $('input[type="checkbox"]').each(function(index, value) {
        if (this.checked) {
            /*add*/ /*get label text associated with checkbox*/
            alsoInterested += ($('label[for="'+this.name+'"]').html() + ', ');
        }
    });
    if (alsoInterested.length > 0) {
        alsoInterested = alsoInterested.substring(0,alsoInterested.length-2);
    } else {
        alsoInterested = '';
    }

console.log(alsoInterested);
  
      var li = $('<li>'+alsoInterested+'</li>').appendTo('#list');
    $("#ul").append(li);
});
$('li').click(function()
{
alert('test');
});

li
{
 float:left;
    width: auto;
    background: #ccc;
    margin:10px;
    display:inline-block;
    cursor: pointer;
}

li:hover::after {
    content: 'x';
    color: white;
    margin: 10px;
    cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="bannanasChk" name="bannanasChk" value="N">
    <label for="bannanasChk" class="light">Bannanas</label>

    <input type="checkbox" id="carChk" name="carChk" value="N">
    <label for="carChk" class="light">Car Monkeys</label>
    
    <input type="checkbox" id="apesChk" name="apesChk" value="N">
    <label for="apesChk" class="light">Apes</label>
    
    <input type="checkbox" id="repairChk" name="repairChk" value="N">
    <label for="repairChk" class="light">Car Repair</label>
        <br>
        
        <ul class="list-unstyled" id="list">
       </ul>

Answer №1

It's evident that managing a list based on checked/unchecked values can quickly become unnecessarily complicated.

A more straightforward approach is to reconstruct an array from the selected options each time a checkbox changes. This array can then be used to display the relevant li elements in your ul, like so:

$(':checkbox').on('change', function() {  
  var $list = $('#list').empty();
  var alsoSelected = $(':checkbox:checked').map(function() {
    var title = $(this).next('label').text();
    $(`<li>${title}</li>`).appendTo($list);
    return title;
  }).get();
  console.log(alsoSelected);    
});
li {
  float: left;
  width: auto;
  background: #ccc;
  margin: 10px;
  display: inline-block;
  cursor: pointer;
}

li:hover::after {
  content: 'x';
  color: white;
  margin: 10px;
  cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="bannanasChk" name="bannanasChk" value="N">
<label for="bannanasChk" class="light">Bannanas</label>

<input type="checkbox" id="carChk" name="carChk" value="N">
<label for="carChk" class="light">Car Monkeys</label>

<input type="checkbox" id="apesChk" name="apesChk" value="N">
<label for="apesChk" class="light">Apes</label>    

<input type="checkbox" id="repairChk" name="repairChk" value="N">
<label for="repairChk" class="light">Car Repair</label><br />

<ul class="list-unstyled" id="list"></ul>

Keep in mind that bind() is outdated and deprecated. It's recommended to use on() instead, as demonstrated above.

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

The Navigation Bar in Vue Component Renders Incorrectly due to Bootstrap Integration

I am facing an issue with my Bootstrap navbar not displaying correctly within my Vue component. It is appearing as a stacked greyed out button, almost like it's assuming it's on a small device. https://i.sstatic.net/yoPvO.png You can find the c ...

Transfer data from button to input field

Trying to create a simple calculator with PHP to submit to my teacher, I have the basic HTML and PHP codes in the same file. However, I am struggling to figure out how to pass the number from a button to the text input in order to create a larger number, ...

Is there a way to get this script running on WordPress?

I'm working with this JavaScript code: $(document).ready(function(){ $("text1").click(function(){ $(this).hide(); }); }); Here's the HTML code: <div class="div1"> <p class="text1">text to appear when the user p ...

Determine the overall width of a JSX element

Is there a way to retrieve the width of a JSX.Element? In a traditional setup, I would typically use something like: const button = document.createElement('button'); document.body.appendChild(button) window.getComputedStyle(button).width However ...

Trouble with JQuery AJAX form submission function not activating during timeout

I have a function that is responsible for submitting forms: function post_form(form_id, type, redir_url) { $( form_id ).submit(function(e) { CheckRequired(e); var postData = $(this).serializeArray(); var formURL = $(this).attr( ...

Creating a tooltip with a left arrow and a bordered design

I am looking to create a tooltip that displays its content after clicking on the tooltip tip icon. Currently, it only works on hover, but I want it to be clickable and mobile responsive. Desktop design should resemble: https://i.sstatic.net/FQPyt.png Mob ...

The outcome from the PHP file was JSON data, refrain from interpreting it as plain text

I've written PHP code in the file update_customer.php to save customer information. <?php date_default_timezone_set('Asia/Ho_Chi_Minh'); $response = array( 'status' => 0, 'message' => '', 'ty ...

Tips for transforming every element of an array into its own array using JavaScript or Loadash

Hello, I have an array that looks like this. I am attempting to convert each element into its own array. I tried using lodash's chunk function but was unsuccessful. [ 'Product 1', 'Product 2', 'Product 3', 'Product ...

Unable to fetch css file in Node.js

I am currently in the process of learning Node.js, but I have encountered a small issue with retrieving data from a css file. Interestingly, when I directly add the data to the index file's code, it seems to work perfectly. Let me share the relevant ...

How to selectively disable buttons in a group using React

I am working with an array of data const projectTypeValues = [ { name: 'Hour', value: 'hour'}, { name: 'Day', value: 'day'}, { name: 'Session', value: 'session'}, { name: 'project', valu ...

How to perfectly align content on a webpage

Can someone help me understand why my webpage is off-centered as it scales up? I have set a minimum width of 1000px, but it still appears to be centered at 30%-70%. Any insights on this issue would be greatly appreciated. <!DOCTYPE html PUBLIC "-//W3 ...

Difficulty with BCRYPT retrieving information from MySQL

As a beginner in programming, I've hit a roadblock and can't seem to find any solutions. I've managed to successfully register users into my database and hash their passwords. Now, I'm trying to implement a login feature for these users ...

Looking to implement a CSS effect that will hide content without removing the space it occupies on the page?

Is there a way to hide specific buttons within the right column of a 3-column table display? I am currently utilizing jQuery to achieve this function. The purpose behind hiding these buttons is to prevent any quick clicks that might interfere with the fa ...

Firebase Hosting integrated with Cloud Functions

Struggling with deploying my functions and hosting. While I have managed to get them working separately on different branches, integrating both hosting and cloud functions is proving to be a challenge. It seems like my cloud function is not deploying succ ...

What is the best way to integrate jQuery Masonry with ES6 modules?

Attempting to utilize the npm package https://www.npmjs.com/package/masonry-layout Following the installation instructions, I executed: npm install masonry-layout --save Then, in my file, import '../../../node_modules/masonry-layout/dist/masonry.p ...

To enable the "Select All" functionality in ag-grid's infinite scrolling feature in Angular 4, utilize the header check box

Is there a way to add a checkbox in the header of ag-grid for selecting all options when using an infinite row model? It seems that the headerCheckboxSelection=true feature is not supported in this model. Are there any alternative methods to include a che ...

Showing particular URL text upon opening a new window using JavaScript

I've encountered an intriguing scenario. In my application, there's a feature that triggers a new window/tab to open when a button is clicked. Upon opening, a predefined HTML page is shown to the user with a specific URL set. I'm curious abo ...

"Setting an index to a button's ID using Jquery: A step-by-step guide

My goal is to assign incrementing index values to button IDs in a loop. For example, if the first button has an ID of 'unique', the second button should have an ID of 'unique0', and the third button should have an ID of 'unique1&ap ...

Create a surplus of information

I'm currently working on a project where I need to replicate all the entries multiple times and then have them spin and gradually land on a color. However, I'm encountering an issue with duplicating the colors without increasing the width. How ca ...

I require the box element within my section element to have a full-width layout

Looking at the code in the image, you can see that I am using MUI components. Within a section, there is a box containing navigation filter links. The red part represents the section, while the white inside is the navigation link bar. My goal is for this b ...