Show the selected checkbox options upon clicking the submit button

Having trouble setting up a filter? I need to create a feature where checked values from checkboxes are displayed in a specific div after submitting. The display should include a 'Clear All' button and individual 'X' buttons to remove each value, just like the image provided.

https://i.sstatic.net/v2Jwl.jpg Can anyone offer assistance?

$(document).ready(function() {
  $('#showmenu').click(function() {
    $('.menu').show("slide");
  });
});

jQuery(document).ready(function(e) {
  function t(t) {
    e(t).bind("click", function(t) {
      t.preventDefault();
      e(this).parent().fadeOut()
    })
  }
  e(".dropdown-toggle").click(function() {
    var t = e(this).parents(".button-dropdown").children(".dropdown-menu").is(":hidden");
    e(".button-dropdown .dropdown-menu").hide();
    e(".button-dropdown .dropdown-toggle").removeClass("active");
    if (t) {
      e(this).parents(".button-dropdown").children(".dropdown-menu").toggle().parents(".button-dropdown").children(".dropdown-toggle").addClass("active")
    }
  });
  e(document).bind("click", function(t) {
    var n = e(t.target);
    if (!n.parents().hasClass("button-dropdown")) e(".button-dropdown .dropdown-menu").hide();
  });
  e(document).bind("click", function(t) {
    var n = e(t.target);
    if (!n.parents().hasClass("button-dropdown")) e(".button-dropdown .dropdown-toggle").removeClass("active");
  })
});

/******************************************/

$(function() {

  $('input[type="checkbox"]').click(
    function() {
      // if($(this).is(":checked")){
      //        $("#div ul").append("<li> value <a href='javascript:void(0);' class='remove'>&times;</a></li>"); 
      //    }

      value = $(this).val();
      if ($(this).is(':checked')) {
        $('<li></li>').appendTo('#div ol').text($(this).val());
      } else {
        value = $(this).val();
        if ($('#div ol').has('li:contains("' + value + '")')) {
          $('#div ol li:contains("' + value + '")').remove();
        }
      }
    });
});


/******************************************/
/******************************************/
.filter-section .container {
  margin-right: 100px;
  margin-left: 100px;
  padding: 0px;
  height: 24px;
}

.filter-section #showmenu {
  margin: 0px;
  margin-right: 34px;
}

.filter-section #showmenu p {
  color: #3f3f3f;
  font-size: 18px;
  font-weight: 600px;
  margin: 0px;
  padding: 0px;
}

.filter-section .menu .nav {
  border-left: 1px solid #3f3f3f;
}

.filter-section .nav {
  display: block;
  margin: 0;
  padding: 0;
  height: 24px;
}

.filter-section .nav li {
  display: inline-block;
  list-style: none;
}

.filter-section .menu .nav .button-dropdown {
  position: relative;
  margin-left: 24px;
  height: 24px;
}

.filter-section .menu .nav li a {
  color: #000;
  background-color: #fff;
  font-size: 18px;
  font-weight: 600;
  text-decoration: none;
}

.filter-section .menu .nav li a span {
  font-size: 26px;
  line-height: 0;
  height: 24px;
  margin-right: 10px;
}

.filter-section .menu .nav li .dropdown-toggle::after {
  display: inline-block;
  margin-left: 12px;
  vertical-align: 2px;
  content: "";
  border-top: 6px solid;
  border-right: 3px solid transparent;
  border-bottom: 0;
  border-left: 3px solid transparent;
}

.filter-section .menu .nav li .dropdown-menu {
  display: none;
  position: absolute;
  left: 0;
  padding: 0;
  margin: 0;
  margin-top: 0px;
  margin-left: 22px;
  text-align: left;
  width: 224px;
  padding: 10px 24px;
}

.filter-section .menu .nav li .dropdown-menu div {
  border-bottom: 1px solid #000;
}

.filter-section .menu .nav li .dropdown-menu div:last-child {
  border-bottom: none;
  padding-bottom: 10px;
  padding-top: 20px;
}

.filter-section .menu .nav li .dropdown-menu.active {
  display: block;
}


/*.nav li .dropdown-menu a {
    width: 150px;
}*/


/****************************************/

.listofslect {
  padding: 0px;
}

.listofslect li {
  padding: 10px;
  font-size: 14px;
  display: inline-block;
  -webkit-transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
  transition: all 0.4s cubic-bezier(0.25, 0.8, 0.25, 1);
}

.name {
  display: inline-block;
  font-size: 14px;
  font-weight: 600;
  padding: 0;
  margin: 0;
  padding-bottom: 14px;
  padding-top: 10px;
}

.name input {
  margin-right: 12px;
}

.button {
  border: none;
  color: white;
  padding: 14px 0px;
  text-align: center;
  font-size: 16px;
  width: 100%;
  cursor: pointer;
  border-radius: 4px;
  background-color: #000000;
}

button:focus {
  outline: 0px dotted;
  outline: 0px auto -webkit-focus-ring-color;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<section>
  <div class="filter-section">
    <div class="container d-flex">
      <div id="showmenu">
        <p> <img src="images/hamburger-icon-open.png"> Filter</p>
      </div>
      <div class="menu" style="display: none;">
        <ul class="nav">
          <li class="button-dropdown">
            <a href="javascript:void(0)" class="dropdown-toggle"><span>&#8226;</span>Learning Modes</a>
            <div class="dropdown-menu">
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="Self paced"/>Self paced</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="Classroom"/>Classroom</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="Live Virtual-Classroom"/>Live Virtual Classroom</label>
              </div>
              <div class="">
                <button class="button">Apply</button>
              </div>
            </div>
          </li>
          <li class="button-dropdown">
            <a href="javascript:void(0)" class="dropdown-toggle"><span>&#8226;</span>Level</a>
            <div class="dropdown-menu">
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="ABC"/>ABC</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="DEF"/>DEF</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="GHI"/>GHI</label>
              </div>
              <div class="">
                <button class="button">Apply</button>
              </div>
            </div>
          </li>
          <li class="button-dropdown">
            <a href="javascript:void(0)" class="dropdown-toggle"><span>&#8226;</span>Role</a>
            <div class="dropdown-menu">
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="JKL"/>JKL</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="MNO"/>MNO</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="PQR"/>PQR</label>
              </div>
              <div class="">
                <button class="button">Apply</button>
              </div>
            </div>
          </li>
          <li class="button-dropdown">
            <a href="javascript:void(0)" class="dropdown-toggle"><span>&#8226;</span>Skills</a>
            <div class="dropdown-menu">
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="STU"/>STU</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="VWX"/>VWX</label>
              </div>
              <div class="">
                <label class="name"><input type="checkbox" class="" id="checkbox4" value="YZ"/>YZ</label>
              </div>
              <div class="">
                <button class="button">Apply</button>
              </div>
            </div>
          </li>
        </ul>
      </div>
    </div>
    <div class="container" id="div">
      <ol class="listofslect"></ol>
    </div>
  </div>
</section>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

For more details, you can also check out the jsFiddle and Codepen links attached.

Answer №1

After some research, I came across a helpful resource that provided a solution to the issue I was facing. The link explained how to retrieve values from checkboxes using jQuery. This particular method involves storing the checked values in an array, which can then be used to address the problem at hand. Below is the code snippet that demonstrates how to capture and print every checked element upon the triggering of the 'submit' event.

var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
   values.push($(this).val());
});

Answer №2

I have found the solution.

Please review the code for reference on how to implement it. View the full page with the CodePen and JSFiddle snippets provided.

// JavaScript Code for Filter Slide Right Script
$(document).ready(function() {
    // Function triggered on button click for sliding menu
    $('#showmenu').click(function() { 
        $('.menu').show("slide");
    });
}); 

// JavaScript Code for Dropdown Menu Interaction 
jQuery(document).ready(function(e) {
    function t(t) {
        e(t).bind("click", function(t) {
            t.preventDefault();
            e(this).parent().fadeOut()
        })
    }
    
    // Click event for dropdown toggle
    e(".dropdown-toggle").click(function() {
        var t = e(this).parents(".button-dropdown").children(".dropdown-menu").is(":hidden");
        e(".button-dropdown .dropdown-menu").hide();
        e(".button-dropdown .dropdown-toggle").removeClass("active");
        
        if (t) {
            e(this).parents(".button-dropdown").children(".dropdown-menu").toggle().parents(".button-dropdown").children(".dropdown-toggle").addClass("active")
        }
    });
    
    // Logic for hiding dropdown on outside click 
    e(document).bind("click", function(t) {
        var n = e(t.target);
        if (!n.parents().hasClass("button-dropdown")) e(".button-dropdown .dropdown-menu").hide();
    });
    
    // On clicking anywhere in document, remove active class from dropdown
    e(document).bind("click", function(t) {
        var n = e(t.target);
        if (!n.parents().hasClass("button-dropdown")) e(".button-dropdown .dropdown-toggle").removeClass("active");
    })
});

// JavaScript Code for Checkbox Interaction 
$(function() {

    $(document).on('click', '.item', function() {
        removeCheckedResult($(this));
    });

    function removeCheckedResult($child) {
        $child.parent().remove();
        $('input[class=mainlist][data-ref=' + $child.data('cb') + ']').prop('checked', false).trigger('change');
    }

    $("button").on("click", function(e){
        var arr =[];
        var arr1 =[];
        $("#results").html('');
        e.preventDefault();
        var count =  document.querySelectorAll("input:checked");
        
        for (i = 0; i < count.length; i++) {
            arr.push(count[i].value);
            arr1.push(count[i].getAttribute("data-ref"));
        }
        
        for (j = 0; j < arr.length; j++) {
         $("#results").append('<li>'+arr[j]+'<a href="#" class="item" data-cb="' + arr1[j] + '"><img src="https://www.kindpng.com/picc/m/504-5042965_close-wrong-cross-black-png-transparent-png.png"></a></li>');
        }
    })
});

// JavaScript Code for Show Hidden Menu Interaction 
$(document).ready(function() {
    $('#show-hidden-menu, #show-hidden-menu1, #show-hidden-menu2, #show-hidden-menu3').click(function() {
        $('.hidden-menu').show("slow");   
    });

    // Handling Clear All functionality
    $('.clear-all').on('click', function () {
        $('#filter-submenu').empty();
        $('.menu .dropdown-menu div input').prop('checked', false);
        $(".mode-sec span").css("color", "#fff");
        $(".level-sec span").css("color", "#fff");
        $(".skills-sec span").css("color", "#fff");
        $(".role-sec span").css("color", "#fff");
    });
});


$(".dropdown-menu input:checkbox").on("change", function() {
    var len = $(".dropdown-menu input[type='checkbox']:checked").length;
            
    if(len > 0) {
        $("#general .counter").text('(' + len + ')');
    } else {
       $("#general .counter").text(' ');
    }
});

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

Subdomain for an Ajax request

Can we use ajax requests to extract data from and fetch information from pages like ? It appears that JavaScript still does not permit subdomain requests. ...

The challenge of transferring documents to the server

There is a form on the webpage where users can select a file and click a button to send it. <form enctype="multipart/form-data"> <input type="file" id="fileInput" /> <button type="button&quo ...

Changes are not being detected in new Angular 2 files

Currently, I am enhancing an Angular 2 project by incorporating new modules. However, the changes I made in these files are not being recognized within the project. I have attempted to research how change detection functions in Angular 2, but have not bee ...

Safari encounters issues with Flexbox child elements that exceed their assigned height dimensions

Encountering a peculiar Flexbox height dilemma specific to Safari. Interestingly, in Chrome, the center div perfectly fills the 100% height of the body div. Contrastingly, on Safari, the center div extends beyond the 100% height of its container; seeming ...

.npmignore failing to exclude certain files from npm package

I'm facing an issue with a private module on Github that I am adding to my project using npm. Despite having a .npmignore file in the module, the files specified are not being ignored when I install or update it. Here is what my project's packag ...

Retrieve JSON data from an external website

I am looking to display the number of players currently playing on a different poker website on my own site. The necessary data is provided in JSON format by this link (tournaments.summary.players). I have tried using a .getJSON request, but it seems like ...

Utilizing HTML5 Drag and Drop feature to track the initial position of the element being dragged

Currently, I am utilizing the HTML 5 Drag and Drop API to create a sortable list with auto scroll functionality. One crucial aspect I am trying to incorporate is the ability to detect which specific part of an element was grabbed by the user. Take a look ...

Ways to trigger an onClick event of one div based on the presence of another div

I'm looking to execute a function when a specific type of button is clicked on my HTML page. I have approximately 10 buttons on the page and I've written the following code to call a function when a button is clicked: $('.divname').ea ...

Iterate through a generic array to populate a table using ng-repeat

In the scenario I'm currently facing, I am working on creating a common reusable table structure using a directive. The goal is to display different JSON data in both the table header and body. Below is the controller code: angular.module('plun ...

When trying to implement appDir and withPWA in next.config.js, an error has been encountered

My next.config.js is set up with next-pwa and an experimental app feature included. const withPWA = require('next-pwa'); module.exports = withPWA({ pwa: { dest: 'public', disable: process.env.NODE_ENV === 'development&ap ...

What is the process for storing user-provided document names in Firestore database entries?

I'm encountering an issue with my API while trying to utilize Firestore for inputting data for login and registration via the API. The problem arises when attempting to add a document entry in the database with the user's input email during regis ...

Launching the webpage with Next.js version 13

Hey there! I'm currently working on implementing a loading screen for my website to enhance the user experience. Since it's quite a large site, I believe a loading screen would be beneficial. However, I'm having trouble getting it to work on ...

Verifying the type and quantity of an item

Looking at a piece of code where a specific condition is being checked, I'm curious to know why someone might want to skip this particular condition. var number = /^\d+/; var type = Object.prototype.toString.call(obj); for(var key i ...

Is it possible to compare two charts in Chart.js in a way that avoids the issue of small values appearing as large as big values?

I am currently working on a production tracking page that features multiple charts. I want to avoid inconsistencies in tracking at first glance. Is there a way to achieve this using chart.js? If not, what would be the best approach to address this issue? ...

The canvas game's animation can only be activated one time

I am currently working on designing a straightforward canvas game: Here is the code snippet located on CodePen var canvas; var ctx; var x = 300; var y = 400; var r = 0; var mx = 0; var my = 0; var WIDTH = 600; var HEIGHT = 400; function circle(x,y,r) ...

What is the best way to incorporate items into Redux reducers?

Incorporating Redux with Next JS, I am faced with the challenge of adding an array of objects to it. Within my application, there exists a form containing multiple inputs, and in order to accommodate these inputs, I have structured a form consisting of 10 ...

Employing ajax with dynamically created buttons in PHP

I'm struggling to figure out what to search for in this situation. I've tried piecing together code from others, but it's just not working for me. My ajax function successfully retrieves data from a database through a php page and displays ...

Add each individual item from the array into the database sequentially

I have a collection of data entries that I need to individually insert into the database, like so: [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] In essence, I plan to use a for..of loop to iterate over this array and add them one by one. If ...

Go to a different page section using MUI 5

I am currently working on a React application and I want to implement a functionality where pressing a button on my Nav Bar will navigate to a specific section on the first page. To achieve this, I have created an onClick function for my button: const onNa ...

Add a product to your shopping cart in Opencart with the help of Ajax manually

My goal is to automatically add a product to the cart when a user clicks on a button using a custom function that I created. Here is the code for the button: <input type="button" value="Add to cart" onclick="addItemsToCart(83); " class="button btn-suc ...