Tips for retrieving selected items in an array object

Within my UI, I have a select field that, on change, populates corresponding data in a div with nested ul and li elements. What I am attempting to achieve is to convert the selected items within the list (which include checkboxes) into an object of arrays upon button click.

My Progress So Far

$(document).ready(function() {
  $("#btn-search").hide();
  var Data = {
    "India A": [
      "Mumbai",
      "Delhi",
      "Kolkata"
    ],
    "India B": [
      "Bangalore",
      "Chennai"
    ]
  }
  var CountersName = Object.keys(Data)

  let dropdown = $("#counterNames")
  dropdown.append('<option selected="true" disabled>Select Counter</option>');
  for (var i = 0; i < CountersName.length; i++) {
    $('<option/>').val(CountersName[i]).html(CountersName[i]).appendTo('#counterNames');
  }
  $("#counterNames").on('change', function() {
    $(".card").show();
    $("#btn-search").show();
    var value = $(this).val();

    $(".card-header").text(value);
    
    var ul = document.getElementById(".list-group");
    ul_innerhtml = "";
    for (i = 0; i < Data[value].length; i++) {
      title = Data[value][i];
      
      var ul_innerhtml = ul_innerhtml + '<li class="list-group-item">' + title + '<label class="switch "><input type="checkbox" class="success"><span class="slider round"> </span></label></li>';
    }
    $(".list-group").html(ul_innerhtml);

  })

});
$("button").click(function() {
  var selected = new Array(); 

  $("input:checkbox[name=type]:checked").each(function() {
    selected.push($(this).val());
  });

  console.log(selected)

});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  float: right;
}


/* Hide default HTML checkbox */

.switch input {
  display: none;
}

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input.success:checked+.slider {
  background-color: #8bc34a;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<div class="container">
  <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
    <label for="counterNames">Select Counter:</label>
    <select class="form-control" id="counterNames">
    </select>

    <div class="card" style="margin: 10px 0; display: none;">

      <div class="card-header"></div>

      <ul class="list-group list-group-flush">


      </ul>
    </div>
  </div>
  <button id="btn-search" class="btn btn-default commonButton" type="submit">
<i class="fa fa-search"></i>&nbsp;Go
</button>
</div>

Upon clicking the 'Go' button, I aim to retrieve the selected option from the dropdown along with the checked items like this

{India A:["Mumbai","Delhi","Kolkata"]}
when India A is chosen. However, my attempt at converting this into an array has resulted in empty output.

Answer №1

There are a total of 3 errors in your code.

  1. You forgot to include the value attribute in your checkbox;
  2. You neglected to specify the name for your checkbox, even though you referenced it when retrieving the value.
  3. You overlooked obtaining the value from the select box, which should be defined as an object and have values pushed into it.

$(document).ready(function() {
  $("#btn-search").hide();
  var Data = {
    "India A": [
      "Mumbai",
      "Delhi",
      "Kolkata"
    ],
    "India B": [
      "Bangalore",
      "Chennai"
    ]
  }
  var CountersName = Object.keys(Data)

  let dropdown = $("#counterNames")
  dropdown.append('<option selected="true" disabled>Select Counter</option>');
  for (var i = 0; i < CountersName.length; i++) {
    $('<option/>').val(CountersName[i]).html(CountersName[i]).appendTo('#counterNames');
  }
  $("#counterNames").on('change', function() {
    $(".card").show();
    $("#btn-search").show();
    var value = $(this).val();

    $(".card-header").text(value);
    // console.log(Data[value]);

    var ul = document.getElementById(".list-group");
    ul_innerhtml = "";
    for (i = 0; i < Data[value].length; i++) {
      title = Data[value][i];

      var ul_innerhtml = ul_innerhtml + '<li class="list-group-item">' + title + '<label class="switch "><input name="type" type="checkbox" class="success" value="' + title + '"><span class="slider round"> </span></label></li>';
    }
    $(".list-group").html(ul_innerhtml);

  })

});


$("button").click(function() {
  var selected = {};
  var type = $("#counterNames").val();
  selected[type] = [];


  $("input:checkbox[name=type]:checked").each(function() {
    selected[type].push($(this).val());
  });

  console.log(selected)

});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  float: right;
}


/* Hide default HTML checkbox */

.switch input {
  display: none;
}


/* The slider */

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input.success:checked+.slider {
  background-color: #8bc34a;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}


/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<div class="container">
  <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
    <label for="counterNames">Select Counter:</label>
    <select class="form-control" id="counterNames">
    </select>

    <div class="card" style="margin: 10px 0; display: none;">

      <div class="card-header"></div>

      <ul class="list-group list-group-flush">


      </ul>
    </div>
  </div>
  <button id="btn-search" class="btn btn-default commonButton" type="submit">
    <i class="fa fa-search"></i>&nbsp;Go
</button>
</div>

Answer №2

Your reasoning has a flaw in that the selector is searching for checkboxes with a name attribute, which you fail to add when appending the li elements on select change.

Additionally, it's important to assign a value to the checkboxes; otherwise, all their values will default to the string 'on', which isn't very helpful.

var ul_innerhtml = ul_innerhtml + '...<input type="checkbox" class="success" name="type" value="' + title + '">...';

Lastly, remember that using map() can generate an array of values from a jQuery object and eliminate the need for a separate each() loop. Here's how:

$(document).ready(function() {
  $("#btn-search").hide();
  var Data = {
    "India A": [ "Mumbai", "Delhi", "Kolkata" ],
    "India B": [ "Bangalore", "Chennai" ]
  }
  var CountersName = Object.keys(Data)
  let dropdown = $("#counterNames")
  dropdown.append('<option selected="true" disabled>Select Counter</option>');
  
  for (var i = 0; i < CountersName.length; i++) {
    $('<option/>').val(CountersName[i]).html(CountersName[i]).appendTo('#counterNames');
  }
  
  $("#counterNames").on('change', function() {
    $(".card").show();
    $("#btn-search").show();
    var value = $(this).val();
    $(".card-header").text(value);

    var ul_innerhtml = "";
    for (i = 0; i < Data[value].length; i++) {
      title = Data[value][i];
      ul_innerhtml = ul_innerhtml + '<li class="list-group-item">' + title + '<label class="switch "><input type="checkbox" class="success" name="type" value="' + title + '"><span class="slider round"> </span></label></li>';
    }
    $(".list-group").html(ul_innerhtml);
  })
});

$("button").click(function() {
  var selected = $(".success:checked").map(function() {
    return this.value.trim();
  }).get();
  console.log(selected)
});
.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
  float: right;
}


/* Hide default HTML checkbox */

.switch input {
  display: none;
}


/* The slider */

.slider {
  position: absolute;
  cursor: pointer;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  -webkit-transition: .4s;
  transition: .4s;
}

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input.success:checked+.slider {
  background-color: #8bc34a;
}

input:checked+.slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}


/* Rounded sliders */

.slider.round {
  border-radius: 34px;
}

.slider.round:before {
  border-radius: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<div class="container">
  <div class="col-xs-12 col-sm-12 col-md-6 col-lg-6">
    <label for="counterNames">Select Counter:</label>
    <select class="form-control" id="counterNames"></select>
    <div class="card" style="margin: 10px 0; display: none;">
      <div class="card-header"></div>
      <ul class="list-group list-group-flush"></ul>
    </div>
  </div>
  <button id="btn-search" class="btn btn-default commonButton" type="submit">
    <i class="fa fa-search"></i>&nbsp;Go
  </button>
</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

The background image is cropped at both the top and bottom edges

Check out this JSFiddle link: http://jsfiddle.net/SoSoDef/uhx3o62f/1/. The code seems to be running fine, but I'm facing an issue where the image is being slightly cut off at the top and bottom for some reason. -webkit-background-size: cover; Can an ...

How can I set a dropdown back to the first index in MVC?

Within my MVC project, I have a dropdown list bound in a div using the code snippet below: @{ List<SelectListItem> lsqty = new List<SelectListItem>(); for (int i = 1; i <= 10; i++) { SelectListItem sl = new SelectListIt ...

Is it possible to perform a PHP redirect after the headers have been

I am encountering an issue with a function that needs to redirect the page once a variable is set. The challenge arises from the fact that this function is located at the bottom of the PHP page. As a result, I have already displayed a significant amount ...

Tips for incorporating the "build" directory into the Travis-CI build process and deployment of an npm module

Currently, I am working with a Typescript module that has a directory ./src And I also have travis-ci set up for the project. language: node_js node_js: - 5.1.0 install: - npm install - npm install -g mocha - npm install -g gulp - npm install -g tsd - ...

What is the reason that when a <div> click on a mobile device includes a jQuery ('#item').fadeOut() function, the CSS of the '#item' element maintains its previous hover state

While creating a mock back to top button, I encountered an issue with my jQuery call to fadeOut() behaving differently on mobile devices (this discrepancy can be observed using any desktop browser simulator). You can find the source code here: https://cod ...

What is the best way to adjust the z-index when hovering over an li element

In my <ul>, each <li> contains an image. I want these images to scale and become opaque upon hover. However, the issue is that when they scale, they get covered by the following image. Unsure if the z-index is correctly placed... Below is the C ...

Out of reach: Menu div slides up on click outside

<a class="btn">Click ME </a> <div class="content"> Content </div> $('.btn').click(function(){ $('.content').slideToggle(); }); Check out the example here Everything is working properly, but I have a q ...

CSS: The addition selection operator is not functioning as expected

The span's background color is not changing correctly when the radio button is changed. Why is this happening and how can it be fixed? div { margin: 0 0 0.75em 0; } .formgroup input[type="radio"] { display: none; } input[type="radio"], label { ...

How can I create a box-shaped outline using Three.js?

As someone new to threejs, I have been trying to figure out how to render a transparent box around a symbol in my canvas. The box should only display a border and the width of this border should be customizable. Currently, I am using wireframe to create a ...

Learn the method for printing CSS outlines and background colors in IE8 using JQuery's printElement feature

Printing my HTML calendar table in Chrome results in a perfect display. However, when I try to print it in IE8, the background colors and images are not included. Despite following steps from a helpful post on setting it as the default option, there were n ...

Tutorial on creating a subset of a series using jqplot

I am looking to display three series on the same canvas. The series are defined as follows: rec1 = [0, 0, 150, 200, 0 ]; rec2 = [60, 120, 179, 240, 300]; rec3 = [50, 100, 150, 200, 250]; Below are the source codes I am using to draw these series. $ ...

Navigating the authorization header of an API request in a Node environment

const authHeader = req.headers["authorization"]; I have a question that may come across as basic - why do we use ["authorization"] instead of just .authorization? After some research, I discovered it had to do with case sensitivity but ...

Cannot retrace steps in file tree using ../

My website has a file structure set up like this: css style.css other files... templates index.html other files... I am attempting to reference the style.css file from my index.html document. My initial attempt was to navigate back a directory u ...

Converting API response into a class instance using `class-transformer` in TypeScript: A step-by-step guide

When working with TypeScript, I have a regular method called Request(method: HttpMethod, url: string, ...) that is used for calling APIs. Now, my goal is to convert the response from this API request into an instance of a class using class-transformer (or ...

Activate the angular function

In the controller below, there is a function that should be triggered when the link is clicked: <a id="1" href="" name="xxx" ng-click="searchall(id)">sample link</a> ng.controller('SearchResultController', ['$scope', &apos ...

How can we eliminate the need for specifying the order of generic arguments in TypeScript?

In the development of my middleware engine, I have incorporated various generic arguments that are specific to the particular implementation in use. export type Middleware< Store = never, Args = unknown, Response = unknown > = ( context: { ...

Numerous attributes for displaying ngOption values

I have an item that resembles the following: $scope.team = [ { name: "John", number: 1 }, { name: "Emma", number: 2 } ]; Currently, in my HTML code, I am using ngOption to populate a dropdown menu with values from the object. < ...

Alignment of Inline SVG in HTML

I am struggling to align an inline SVG within a bounding DIV correctly, as shown in this example. <!DOCTYPE html> <html> <body> <div style="border: 1px solid black; height: 50px; width: 100px; vertical-align:top;"> < ...

Uncovering secret divs with the power of jQuery timing upon reload

Currently, I am in the process of developing a custom Wordpress theme for my blog which includes an overlay-container. When a button is clicked, this container slides in from the top and pushes down the entire page. To achieve this functionality, I am uti ...

Fetching information through AJAX in NodeJS and saving it in a database

I am facing an issue with retrieving data from the client side in my NodeJS application. I have prepared JSON data on the client side, which can be viewed in this codepen link. On the server side, I am attempting to receive this data from the client: var ...