Search code examples
jqueryarraystextcheckbox

Add Commas to checkbox array text Output


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


Solution

  • 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.