Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

263
Visualizações
jQuery count checkboxes and group count by data-attribute

I have a number of html checkboxes that I am trying to count like this...

    jQuery('.mycheckboxes').change(function() {
      var count = jQuery('.mycheckboxes:checked').length;
      console.log(count);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">

This is working correctly, but I want to create something like an array which will group the count of clicked checkboxes by the data-section attribute, so my output would look something like...

{
    data-section-1 : 4,
    data-section-2 : 3,
    data-section-3 : 1,
};

What is my best approach, I am more used to using PHP so would be trying to create an array, but should I be using an object instead?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

This is vanilla JavaScript, but should work for you:

let finalArray = [0,0,0];
const dataSections1 = document.querySelectorAll("[data-section='1']");
const dataSections2 = document.querySelectorAll("[data-section='2']");
const dataSections3 = document.querySelectorAll("[data-section='3']");
dataSections1.forEach((function(item) {
  if (item.checked) {
    finalArray[0]++;
  }
});
dataSections2.forEach((function(item) {
  if (item.checked) {
    finalArray[1]++;
  }
});
dataSections3.forEach((function(item) {
  if (item.checked) {
    finalArray[2]++;
  }
});
about 4 years ago · Juan Pablo Isaza Relatório

0

Don't need jquery (stay away from the bloatware). Simply create an object and use section attribute value as it's keys:

const count = {};
for(let i = 0, list = document.querySelectorAll(".mycheckboxes"); i < list.length; i++)
{
  count[list[i].dataset.section] = 0; //set initial values for each section
  list[i].addEventListener("change", onChange);
}

function onChange(e)
{
  count[e.target.dataset.section] += e.target.checked ? 1:-1;

  console.log(count);
}
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
<input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">

about 4 years ago · Juan Pablo Isaza Relatório

0

Get list of keys, set their value to 0. Create an object from those keys. Then iterate and populate.

  $('.mycheckboxes').change(function() {
      var items = $('.mycheckboxes:checked').toArray();
      let keyvalueArray = items.map(v => (["data-section-" + $(v).attr("data-section"), 0 ]));
      let sections = Object.fromEntries([... new Set(keyvalueArray)]);      
      items.forEach(v => { sections["data-section-" + $(v).attr("data-section")] +=1; })
      console.log(sections);
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="1" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="2" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">
    <input type="checkbox" class="mycheckboxes" data-section="3" name="mycheckboxes">

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda