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

127
Visualizações
How to push checkbox checked values to js object using jquery each function?

I want the checked checkbox values to store in food javascript object like below:

food: {
{id: 1, name: egg }
{id: 2, name: meat}
}

Here's my code:

var exclude_foods = {};

jQuery('input[name=exclude_food]:checked').each(function(){
   exclude_foods = Object.assign(exclude_foods, {
     id: 1,
     name: jQuery(this).val(),
   });
});

Any suggestion or help?

almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can use jQuery's map() method to do what you require.

Note that it's not clear where the id value is intended to come from, so I set it to the index of the checkbox for this example. This can easily be amended to suit your use case.

$('button').on('click', e => {
  var exclude_foods = {
    foods: $('input[name="exclude_food"]:checked').map((i, el) => ({
      id: i,
      name: el.value
    })).get()
  };
  console.log(exclude_foods);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<label>
   <input type="checkbox" name="exclude_food" value="egg" />
   Egg
</label>
<label>
   <input type="checkbox" name="exclude_food" value="meat" />
   Meat
</label>
<label>
   <input type="checkbox" name="exclude_food" value="nuts" />
   Nuts
</label>

<button>Get values</button>

almost 4 years ago · Santiago Trujillo 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