Array of Checkboxes

Seeking assistance with a coding dilemma. Here is the existing code snippet:

<section>
  <span class="tags"></span>

  <label for="shoes">Shoes</label>
  <input type="checkbox" id="shoes">

  <label for="jeans">Jeans</label>
  <input type="checkbox" id="jeans">

  <label for="tops">Tops</label>
  <input type="checkbox" id="tops">
</section>

<section>
  <span class="tags"></span>

  <label for="monkey">monkey</label>
  <input type="checkbox" id="monkey">

  <label for="lion">lion</label>
  <input type="checkbox" id="lion">

  <label for="dog">dog</label>
  <input type="checkbox" id="dog">
</section>

Each 'section' is generated dynamically. I am struggling to figure out how to insert the value of each input into the respective span within the section when checked. I have attempted using Arrays, but the dynamic nature of the sections is causing issues.

Could anyone lend me a hand with this? Your help would be greatly appreciated.

Answer №1

It's a good idea to assign each checkbox input a value, but in this case, I'll use id instead.

// To track all checkboxes
$('section input[type="checkbox"]').click(function(e) {
    var $this = $(e.target);
    // Locate the parent container.
    var $parent = $this.parent('section');
    // Find all checked checkboxes.
    var checked = $parent.find('input[type="checkbox"]:checked');
    // Store values or ids in an array.
    var result = $.map(checked, function(ele) {
        return $(ele).attr('id');
    });
    // Display the result as needed.
    $parent.find('.tags').text(result.join(' '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section>
  <span class="tags"></span>

  <label for="shoes">Shoes</label>
  <input type="checkbox" id="shoes">

  <label for="jeans">Jeans</label>
  <input type="checkbox" id="jeans">

  <label for="tops">Tops</label>
  <input type="checkbox" id="tops">
</section>

<section>
  <span class="tags"></span>

  <label for="monkey">Monkey</label>
  <input type="checkbox" id="monkey">

  <label for="lion">Lion</label>
  <input type="checkbox" id="lion">

  <label for="dog">Dog</label>
  <input type="checkbox" id="dog">
</section>

Answer №2

Here is a sample JavaScript code snippet:

<script type="text/javascript></br>
window.addEventListener("load",function(){</br>
    var sections = document.getElementsByTagName("section");</br>
    for(var i=0; i<sections.length; i++){</br>
        var n = 0;</br>
        sections[i].span = sections[i].getElementsByTagName("span")[0];</br>
        sections[i].checkboxes = [];</br>
        var inputs = sections[i].getElementsByTagName("input");</br>
        for(var c=0; c<inputs.length; c++){</br>
            if(inputs[c].type!="checkbox"){continue}</br>
            sections[i].checkboxes[n++]=inputs[c];</br>
            inputs[c].onchange=function(){this.parentNode.getValues();}</br>
        }</br>
        sections[i].getValues = function(){</br>
            var o=[], n=0;</br>
            for(var i=0; i<this.checkboxes.length; i++){if(this.checkboxes[i].checked){o[n++] = this.checkboxes[i].id}}</br>
            this.span.innerHTML = o.join(", ");</br>
        };</br>
    }</br>
},false);</br>
</script></br>

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

Is it possible for me to access a portion of a variable?

Is it feasible to extract a segment of a variable and utilize it in a where loop? function report_detail_costs($clientID){ $this->db->from('Project'); $this->db->join('Kosten', 'Kosten.idPro ...

Nested JSON data within an array using Httpful

For the past 3 days, I've been attempting to use PHP and httpful to display the ID from a test JSON file without success. Despite trying various combinations and even attempting to create a handler to decode the data as an array, I just can't se ...

Issue when sending PHP Papa Parse object through AJAX

I am currently working on extracting a CSV local file in PHP using AJAX and have found success with Papa Parse. However, I am facing difficulties passing the results with AJAX. Despite trying various methods such as JSON.stringify, passing only the first f ...

"Enhancing user experience: dynamically adding rows using a combo of jquery, ajax, and php

This is the layout of my table. Here is the result I'm getting. Below is the code snippet: <table width="100%" id="controltable" border="1"> <tr> <th> Product Name </th> <th> Product Pri ...

npm replace: troubleshooting npm script for replacing text across numerous files

I am currently attempting to swap out keywords in multiple files across various folders using regular expressions for the path: ./dist/src/**/**/**/*.scss Here is the npm script I am using: "build:src:replace:icon": "replace 'foo' 'bar&apos ...

Tips for addressing dependency issues in react native applications

Starting a new ReactNative project using "react-native init newProject" is giving me some warnings. How can I resolve these issues? npm WARN deprecated [email protected]: core-js@<2.6.5 is no longer maintained. Please, upgrade to core-js@3 o ...

Javascript does not have the capability to parse JSON

Received a JSON response from a PHP file: [ { "color": "black", "product_name": "Prod2", "revision": "apps/" }, { "color": "green", "product_name": "Prod1", "revision": "dev/" } ] (successfu ...

The dynamic data graph generated by HIGHCHARTS Areaspline is not as effective as expected

I need help creating a Dynamic Areaspline graph, but the result is coming out strangely. Does anyone have any ideas on how to fix this and get a smooth series? Here is an example of the issue: http://jsfiddle.net/mchc59nb/1/ chart: { ...

Ways to dynamically update the class name of pre-existing elements in React.js

element, I am currently working on a memory game project where I aim to provide visual feedback to the player when they guess the correct or incorrect answer. Instead of just outputting 'CORRECT' or 'WRONG' to the console, I want the ex ...

MUI options - The specified type 'string' cannot be matched with type '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'

Is it possible to utilize custom variants in MUI v5? I am having trouble using a custom variant according to their documentation: https://mui.com/material-ui/customization/theme-components/#creating-new-component-variants declare module "@mui/material ...

The PHP script is not being activated by AJAX

I am completely baffled by the situation at hand. Sometimes, I open a different browser to test my changes and it works as expected. But then, when I try again, it fails. It's driving me crazy. On syllableapp.com, I set up a MySQL database that I can ...

Strategies for organizing and handling npm packages within my codebase

Recently, I decided to create a discord bot and used npm for the first time. After setting up my package file and installing discord.js, I now find myself with 3000 files that could be synced to my repository. It seems like an overwhelming situation, and I ...

Express routes are malfunctioning

I have a situation with two different routes: /emails and /eamils/:id: function createRouter() { let router = express.Router(); router.route('/emails/:id').get((req, res) => { console.log('Route for get /emails/id'); }); ...

Is it possible to read an XML response as a stream using Ext JS?

Requesting an XML response can sometimes result in a slow completion time due to certain constraints. Despite this, the data begins returning quickly. I am wondering if it is feasible to read the response stream in Ext JS before it is fully complete. My u ...

What is the process for removing a row from the database in this scenario?

My current goal is to implement a functionality where clicking on the "Delete" button will remove a file from the server and also delete the corresponding database entry with the same file name. The file deletion process on the server works perfectly, but ...

Incorporate the use of OpenLayers into a Vue.js application

Can anyone share their insights on incorporating Openlayers into a Vuejs project? I'm looking to showcase various layers within my Vue app. Thanks in advance! ...

What is the significance of curly braces within function parameter declarations in JavaScript?

Recently, I have been exploring a tutorial that delves into setting up React with Redux. While following along, I came across some unfamiliar syntax involving curly braces within function parameter definitions. Can someone explain what purpose these serve? ...

Import data from a file into a JavaScript 2D array

Looking for a way to load an array from a text file in JavaScript? Here's what I have: var linePoints = [[0, 3], [4, 8], [8, 5], [12, 13]]; But rather than defining it in the code, I'd like to read it from a text file. The file looks like this: ...

Leveraging React useEffect for retrieving data and managing component behavior

Having trouble querying data, setting it to state with useEffect, and rendering the results? I've tried a few things but only see changes when state is updated. Any advice would be greatly appreciated. Thank you in advance. useEffect // fetchCamp ...

Having trouble with jQuery toggle fade: Unable to make the div fade in/out when toggling

Is there a way to modify the functionality of my black button so that when clicked, the red div fades out while the blue div fades in? Right now, clicking the button switches between the two divs without any fading effect. Fiddle: http://jsfiddle.net/ddac ...