Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

62
Vistas
Merge multiple checkboxes groups into one array with javascript

I have form with checkboxes groups, like so:

<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">

What I'm trying to achieve is on form.change() I would like to have an array with keys of checkboxes names and array of the values, like so

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

checkboxes.each(function () {

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

 myArray[name] = val;

});

As a result I'm trying to get an array with 'name' as keys and 'val' as an array, like so:

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

I hope this make sense. Thank you for any help in advance!

7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Your desired output should in fact have the array and plain-object notation swapped. The outer structure is a plain object with named keys, while the inner structure is an array of values:

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

So you need to initialise the outer structure as a plain object, and maybe name it as plural:

var myArrays = {};

Then, in your loop, check if you already have a value for the given key. If not, create an array with [] and add the value to that. Otherwise, add the value to the array that was already there:

$("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>

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.