0

Every time I check a checkbox the value gets pushed into an array and I want to append it to a div but each item should be in it's own div.

$(document).ready(function() {
    $('input[name="size"]').on('click', function() {
        var size = $(this).val();
        $('.selected-sizes').empty();

        var selectedSize = new Array();
        $('input[name="size"]:checked').each(function() {
            selectedSize(this.value);
            $('.selected-sizes').append('<div class="size-chosen"><span>' + selectedSize + '</span></div>');
        });
    });
});

But this code I have adds the entire array onto each new line.

small
small, large
small, large, medium

Is it possible to put each item in the array on its own Line like:

small
large
medium

If I put the append outside of the each loop then it shows each item separated by a comma on the same line instead of each on a new line/in own div.

Current outputted html:

<div class="selected-sizes">
    <div class="size-chosen"><span>small, large, medium</span></div>
</div>

Required output:

<div class="selected-sizes">
    <div class="size-chosen"><span>small</span></div>
</div>
<div class="selected-sizes">
    <div class="size-chosen"><span>large</span></div>
</div>
<div class="selected-sizes">
    <div class="size-chosen"><span>medium</span></div>
</div>
user10980228
  • 597
  • 1
  • 6
  • 21
  • can you include html content please – Nijin P J Sep 16 '19 at 09:02
  • can you give a detailed example with some example HTML about what are you trying to achieve, your question isn't quite clear. – Jaspreet Singh Sep 16 '19 at 09:03
  • instead of looping all checked why aren't you just adding the one that currently gets checked? – Pete Sep 16 '19 at 09:09
  • @Pete, because I was having trouble removing it from the list when I unchecked it. I also need al the values to go into a form to be submitted so seemed like a good idea to have that data in an array but perhaps there is a better way? – user10980228 Sep 16 '19 at 09:11
  • I actually think I figured it out. `selectedSize.push('
    ' + this.value + '
    ');`
    – user10980228 Sep 16 '19 at 09:14

2 Answers2

1

I think the current output according to your code should be

<div class="selected-sizes">
    <div class="size-chosen"><span>small</span></div>
    <div class="size-chosen"><span>small, large</span></div>
    <div class="size-chosen"><span>small, large, medium</span></div>
</div>

Try this

$(document).ready(function() {
$('input[name="size"]').on('click', function() {
    var size = $(this).val();
    $('.selected-sizes').empty();

    var selectedSize = new Array();
    $('input[name="size"]:checked').each(function() {
        selectedSize.push(this.value);
        $('.selected-sizes').append('<div class="size-chosen"><span>' + this.value + '</span></div>');
    });
});
});

Also to push into an array you should use push method (Reference).

Jaspreet Singh
  • 399
  • 2
  • 8
1

I would add and remove each one separately rather than doing an each loop

var $container = $('.selected-sizes'),
    $inputs = $('input[name="size"]');

$inputs.on('click', function() {
  var currentValue = this.value,
      currentIndex = $inputs.index(this); // need this for sorting
  
  if (this.checked) {
    $container.append('<div class="size-chosen" data-index="' + currentIndex + '"><span>' + currentValue + '</span></div>'); // append the clicked item to the container
    
    var sorted = $('.size-chosen').sort(function (a, b) {
        var contentA = parseInt($(a).data('index'), 10);
        var contentB = parseInt($(b).data('index'), 10);
        return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
     });            // this will sort the divs into the same order as your inputs - not sure if you want this, can be removed if you don't
     
    $container.html(sorted);  // update the container with the sorted divs
  } else {
    $container.find('.size-chosen').filter(function() {
      return $(this).text() === currentValue;              // filter the divs on the uncjecked value
    }).remove();    // remove the div if the checkbox is unchecked
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="size" value="small">
<input type="checkbox" name="size" value="medium">
<input type="checkbox" name="size" value="large">
<div class="selected-sizes"></div>
Pete
  • 57,112
  • 28
  • 117
  • 166
  • Thanks Pete, is there a particular reason you prefer this? I have a hidden field in a form that needs to send the details in a contact form. Wouldn't it be better to have those values in an array in one hidden field? – user10980228 Sep 16 '19 at 10:24
  • Why not make your checkboxes send the data directly in their own array? – Pete Sep 16 '19 at 10:26
  • Makes sense. But I am just trying to understand if there is an added benefit to doing it this way as opposed to putting it in an array from the start. Performance? Or why do you prefer this method? I want to do what is 'best' so just trying to understand why. – user10980228 Sep 16 '19 at 10:28
  • Not sure really, just think if you are binding a function to the click, it shouldn't have to re-get all the values of the other checkboxes, if it wasn't for the sort I would say it would be slightly better on performance but with such a small array I guess it really doesn't make much difference – Pete Sep 16 '19 at 10:35
  • Sorry, last question. If I didn't want these each in their own divs, but separated by commas in the same div, should I still use your code but try modify it or use the array way again? – user10980228 Sep 16 '19 at 11:31
  • 1
    If all you want is a comma seperated list, then I would do it like this: https://stackoverflow.com/questions/9593237/jquery-checkbox-values-to-comma-separated-list, probably closer to your original – Pete Sep 16 '19 at 11:32