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

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源