dongqian5569 2017-06-16 03:25
浏览 201
已采纳

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 03: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条)
编辑
预览

报告相同问题?