1

I need "," between values (Commas or new line)
Output now: ab
Expected output: a,b

I'm just not sure where place it exactly. I get an extra comma every time at the start or at the end, like ",a,c" OR "a,c,".

$('.check').click(function() {
  $("#text").val('');
  $(".check").each(function() {
    if ($(this).prop('checked')) {
      $("#text").val($("#text").val() + $(this).val());
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="a" class="check" id="a" value="a"><label for="a"> a</label><br>
<input type="checkbox" name="b" class="check" id="b" value="b"><label for="b"> b</label>
<br>
<input type="checkbox" name="c" class="check" id="c" value="c"><label for="c"> c</label><br>
<input type="text" name="text" id="text">
Kallados
  • 17
  • 7
  • 1
    One way is to concatenate a comma along with each new value. Another way is to build an array of values and [join](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join) them with a comma. What have you tried and where do you get stuck? – showdev Mar 12 '21 at 22:42
  • Thx for Input. just edited the Question to get it clearly. – Kallados Mar 12 '21 at 23:12

1 Answers1

1

I recommend selecting all checkboxes, filtering to only checked boxes, mapping values to an array, and joining the array by a comma.

let $checks = $('.check');

$checks.on('click', function() {

  let values = $checks
    .filter(':checked')
    .map((k, box) => box.value)
    .toArray()
    .join(',');

  $("#text").val(values);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="a" class="check" id="a" value="a"><label for="a"> a</label><br>
<input type="checkbox" name="b" class="check" id="b" value="b"><label for="b"> b</label>
<br>
<input type="checkbox" name="c" class="check" id="c" value="c"><label for="c"> c</label><br>
<input type="text" name="text" id="text">

Also see jQuery get values of checked checkboxes into array.

showdev
  • 28,454
  • 37
  • 55
  • 73