Combining several groups of checkboxes into a single array using JavaScript

I am working on a form that contains checkbox groups, structured like this:

<input type="checkbox" name="group_one" value="1">
<input type="checkbox" name="group_one" value="2">
<input type="checkbox" name="group_two" value="1">
<input type="checkbox" name="group_two" value="2">

My goal is to create an array with keys representing the checkboxes' names and values as arrays of their selected values when the form changes. Here is the JavaScript code I have so far:

var checkboxes = $('input').filter(':checked');
var myArray = [];

checkboxes.each(function () {

 var name = $(this).attr('name');
 var val  = $(this).val();

 myArray[name] = val;

});

The desired outcome is to have an array where 'name' serves as keys and 'val' as arrays, similar to this format:

[group_one: {1,2}, group_two: {1,2}]

I hope this explanation makes sense. Thank you in advance for any assistance!

Answer №1

In order to achieve your desired output, you should switch the array and plain-object notations. The outer structure should be a plain object with named keys, while the inner structure should consist of arrays of values:

{group_one: [1,2], group_two: [1,2]} 

To accomplish this, start by initializing the outer structure as a plain object, perhaps naming it in the plural form:

var myArrays = {};

Next, within your loop, verify if a value already exists for the given key. If not, create an array using [] and add the value to it. Otherwise, append the value to the existing array:

$("form").change(function () {
  var checkboxes = $('input').filter(':checked');
  var myArrays = {};

  checkboxes.each(function () {
    var name = $(this).attr('name');
    var val  = $(this).val();
    if (!(name in myArrays)) myArrays[name] = [];
    myArrays[name].push(val);
  });
  $("pre").text(JSON.stringify(myArrays, null, 2)); // For debugging
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  <input type="checkbox" name="group_one" checked value="1">Option 1
  <input type="checkbox" name="group_one"         value="2">Option 2
  <input type="checkbox" name="group_one" checked value="3">Option 3
  <br>
  <input type="checkbox" name="group_two"         value="1">Option 1
  <input type="checkbox" name="group_two" checked value="2">Option 2
  <input type="checkbox" name="group_two" checked value="3">Option 3
</form>
<pre></pre>

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

Experiencing difficulties with displaying the values of an array in Java

When working in Java, I encountered an issue with my print command while trying to output a simple list of values using an array. Can you spot the mistake in my code snippet below? public class BasicArrayTest { public static void main(String[] ...

Utilizing the power of HTML datalist and *ngFor to present one value while sending another

I am currently working on a project that involves creating an autocomplete text box using the <datalist> tag with *ngFor functionality. However, the code I am using is showing both the value declared with [value] and the input between the <option& ...

Encountered an error while trying to create module kendo.directives using JSPM

I am attempting to integrate Kendo UI with Angular in order to utilize its pre-built UI widget directives. After running the command jspm install kendo-ui, I have successfully installed the package. In one of my files, I am importing jQuery, Angular, and ...

What is the process for filling a table with data sourced from Firebase?

I have successfully used the code below to populate a datatable table with data from a JSON file. However, I am now attempting to populate the table with data from Google's Firebase database. The issue arises because new data pushed into Google's ...

How can I prevent tinymce from stripping out my <link> tag?

I'm having an issue with tinymce. dd<script id="kot-id" src="***insert link here***"></script><div id="kotcalculator"></div><link rel="stylesheet" href="***insert link here***" type="text/css" media="screen" /> It seems ...

Experiencing issues with applying bootstrap style to pagination when using react-js-pagination

I am currently utilizing the react-js-pagination library to showcase page numbers within my application. Bootstrap has been included in the public/index.html file and can be accessed using className in other components. When it comes to the Pagination com ...

AngularJS faces issue with view not reflecting changes made to model

A web-based game I am developing lets players bid on cards and trade them with one another. The technology stack for this application includes Node, Express, MongoDB, and Angular. The player avatars and names, along with their connection status, are displ ...

What could be causing the data toggle feature in my navbar to not work on Bootstrap?

Here is a code snippet to create a simple collapsible navbar with Bootstrap 5 that includes a logout button. However, the data toggle feature for the logout button doesn't seem to work when clicked. Any suggestions on how to fix this? <!DOCTYPE ...

Is there a way to hide the row select option for individual rows in MUIDatatables without affecting the multiple row select options?

Is there a way to hide the checkbox in the header row that allows selection of all rows at once? I prefer to manually select multiple options by clicking on each individual row. Can the row select option be hidden? https://i.sstatic.net/dfiJQ.png ...

Error message HMR Webpack was found to be invalid

When using Webpack, I keep encountering the following error message: Invalid HMR message, along with a lengthy JSON string. Unfortunately, I couldn't find any helpful resources to assist me in debugging this issue. Do you have any suggestions? https ...

Adjust the Height of a Pair of Floating DIVs on the Fly

I have completed the coding using Visual Studio 2008. On my webpage, I have two div sections named "dvLeftContent" and "dvRightContent". The issue I am facing is that I cannot set a static height for these divs because the height of "dvRightContent" vari ...

Enhance nested IFELSE statements in TypeScript

While working on a personal project, I find myself dealing with multiple conditions. I'm wondering if there's a more efficient way to handle this as the current code appears somewhat messy with all these IFELSE statements. public static async ha ...

Ensure consistency in CSS3 background color transitions

There are multiple elements on the webpage with background transitions that change from one color to another: @-moz-keyframes backgroundTransition /* Firefox */ { 0% {background-color:#ff7b7b;} 33% {background-color:#7fceff;} 66% {backgr ...

Arranging a collection of strings using the qsort function

I'm organizing an array of strings by utilizing the qsort method. char treeName[100][31]; After some experimentation, I discovered that it can be done as follows: qsort(&treeName[0], count, sizeof(*treeName), Comparar_nome); However, I am uncert ...

Obtain and showcase the index of the checkbox that has been selected

Is there a way to display the position of a checkbox when it is checked using JQuery? For instance, if Monday is checked, it should display position 0 and if Sunday is checked, it should show position 6. I have tried using .index() but it keeps returning 0 ...

Can you explain the purpose of the "letter:" included in the code and how it is utilized?

g: function testFunction() { return true; } h: function anotherTestFunction() { } i: console.log('test') I'm intrigued by the mystery of this code snippet. As is written, I am executing it in NodeJS version 16 or higher and trying to un ...

A guide on assigning a state variable to a dynamically generated component within a React application

I need to display user data from an array and have a button for each watchlist that deletes it. Although the backend is set up with a function deleteWatchlist, I am facing an issue in setting the state of the watchlistName for each watchlist after mapping ...

Obtaining the text from an element in Selenium using JavaScript

I've been trying to figure this out, and it seems like it should be a simple task, but how can I extract the text from a table displayed in a browser? When I use the "inspect" tool, the code snippet looks something like this: <tr role="row&qu ...

I am having trouble getting Highcarts to load the JSON data

I am currently in the process of utilizing Highcharts to generate a chart. The JSON output I have is in standard format and was generated using PHP's json_encode() function. Below is the JSON output: [["2015-07-13 16:41:05","3"],["2015-08-15 16:41:05 ...

Determine in jQuery whether a Value is present within a JSON dataset

[ { "link" : "images/examples/image-3.png", "image" : "images/examples/image-3.png", "title" : "copy" }, { "link" : "images/examples/image-3.png", "video" : "video placeholder", "title" : "c ...