dongqiya9552 2018-07-16 13:27
浏览 67
已采纳

获取选中的值

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.

  • 写回答

1条回答 默认 最新

  • dongsi5381 2018-07-16 13:34
    关注

    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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?