When I check my box on the left, I would like to retrieve the value in an input field and when I uncheck it it removes the value from the field. But it should also be that when I check several checkboxes it adds all the values in the input field and separates the data with a comma. How is it possible to do this? Here is what my code looks like.
My JS
function checkedUsers() {
$("input[type='checkbox']:checked").each(
function () {
if (!$(this).is(':checked')) {
$('.product-message').val();
} else {
$('.product-message').val($(this).val());
}
});
}
My tpl (smarty)
{foreach from=$familyUser item=user}
{if $user.active == 1 && {math equation="floor(age / 365)" age=$user.age} <= 16}
<div class="input-group mb-3">
<div class="input-group-prepend">
<div class="input-group-text">
<p>
<input type="checkbox" value="{$user.id_block_family}" id="userChecked" name="userChecked[]" onclick="checkedUsers();">
{$user.surname|escape:'htmlall':'UTF-8'} {$user.name|escape:'htmlall':'UTF-8'}
</p>
</div>
</div>
</div>
{/if}
{/foreach}
Thank you for your help.
One of the simplest ways to do this is to simply rebuild the value each time, from the checkboxes that are still checked. That way you do not have to keep track of which value was removed.
function checkedUsers() {
//set the value to all the selected values, separated by a comma
$('.product-message').val(
$(":checkbox:checked").map(function(){ return this.value; }).get().join(', ')
);
}
</div>