抓取复选框值并将它们放在数组

时间:2017-12-23 06:04:26

标签: javascript jquery

检查下面的JS代码。我的目标是将所有选中的复选框属性称为“价格数据”,并使用<h4 "id="totalDisplay"append()内显示总和。

我还需要添加每个复选框值的数组集合,现在是102和103.整个内容将根据复选框选择进行更新。我的意思是h4显示值和数组集合值都将根据用户复选框选择实时更新。 valueCollections变量用于存储数组值。我是jQuery的新手,这就是为什么我不知道如何实际总和和存储数组值。问你可能有的任何问题。提前谢谢。

$(document).ready(function() {
  var valueCollections[];
  $(".checkbox").on("click", function() {
    $('[price-data]').each(function() {
      $("#totalDisplay").append("<span class=\"label label-warning\">Total price: 70.50</span>");
    });
    $("#submitData").on("click", function() {
      $.post("/Controller/Method", {
        vales: valueCollections
      }).done(function(data) {
        //whatever goes here
      });
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
  <label><input type="checkbox" price-data="50.50" value="102">option1</label>
</div>
<div class="checkbox">
  <label><input type="checkbox" price-data="20" value="103">option2</label>
</div>
<h4 id="totalDisplay"></h4>
<button class="btn btn-default" id="submitData">Submit</button>

2 个答案:

答案 0 :(得分:3)

如果2l.panprice-data总价并且显示已选中array,您可以在checkbox中收集checked,在另一个上收取价值。见下文:

checkbox
var valueCollections = [];
var priceCollections = [];

$("input[type='checkbox']").on("click", function() {
  var priceData = $(this).attr('price-data');
  var val = $(this).val();

  // get checked

  if ($(this).is(':checked')) {
    valueCollections.push(val); // push if checked
    priceCollections.push(priceData);
  } else {
    valueCollections.splice($.inArray(val, valueCollections), 1); // remove if not checked
    priceCollections.splice($.inArray(priceData, priceCollections), 1);
  }

  // sum array

  var sum = eval(priceCollections.join("+"))
  $('#totalDisplay').html(sum);

  console.log(valueCollections);
});

答案 1 :(得分:0)

我做了a fiddle here,但你必须改进它,例如:

HTML:

<div class="checkbox-set">

</div>

<div id = "result">

</div>

JS:

var id = "";
for(i=1 ; i<8 ;i++){
    id="checkbox_"+i;
    $('.checkbox-set').append('<input type="checkbox" id="'+ id +'" value="Click on me"/> <label for="'+id+'">Click on me</label> <br/> ');
}
var selected = [];


$('input[type="checkbox"]').change(function() {
    if(this.checked) {        
        $(this).each(function(){
        selected.push($(this).attr('id'));
        $("#result").html(selected);
        });
    }
    if(!this.checked) {
         const index = selected.indexOf($(this).attr('id'));
         var tt= selected.splice(index, 1);
             $("#result").html(selected);
    }
})

它只是一个示例,而不是完整的代码,我希望您参与其中并做一些努力来实现您的需求:)

相关问题