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

2
  • 1
    One way is to concatenate a comma along with each new value. Another way is to build an array of values and join them with a comma. What have you tried and where do you get stuck? Commented Mar 12, 2021 at 22:42
  • Thx for Input. just edited the Question to get it clearly. Commented Mar 12, 2021 at 23:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.