dongqian5569 2017-06-16 11:25
浏览 200
已采纳

jQuery输出另一个复选框上分隔的两个复选框逗号的数据值

Suppose I have two checkbox like these (can be 100 checkboxes as it will be coming in a while loop)

<input type="checkbox" value="20" data="Apple">
<input type="checkbox" value="30" data="Mango">

And I have two textboxes where I want to output values 20+30 = 50 and Apple, Mango.

<input type="text" id="value1"> // to output sum of values i.e., 50 
<input type="text" id="value2"> // to output comma separated data values Apple, Mango on select

Here I am able to do the first operation. But I am not sure how to do the second one. what I want is when I check the boxes its sums values and outputs it on 1st text box and when unchecks any box it deducts the values back (its already working as I was able to do it) and the second box should output values Apple, Mango when both boxes are checked respectively. If any box is unchecked say box with data value Mango then the textbox value will become Apple (even comma gets removed) only. How to do this? Here is my currennt jQuery code below for completing the 1st operation. How to do the second one? What else should I add here in this code?

$(document).ready(function(){
  $('input[type=checkbox]').change(function(){
    var total = 0;
    $('input:checkbox:checked').each(function(){
      total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
    });
    $("#costdisplay").html(total);
    $("input[name=amount]").val(total);
  });
});
  • 写回答

4条回答 默认 最新

  • drnf593779 2017-06-16 11:29
    关注

    Try this

    $(document).ready(function(){
      $('input[type=checkbox]').change(function(){
        var total = 0;
        var txt = '';
        $('input:checkbox:checked').each(function(){
          total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
          txt += $(this).attr('data')+', ';
        });
        $("#costdisplay").html(total);
        $("input[name=amount]").val(total);
        $("#value2").val(txt.slice(0,-2));
      });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算