Kevin himch Kevin himch - 11 months ago 99
jQuery Question

Grab checkbox values and put them inside an array

Check the JS code below. My target is to make a total of all selected checkbox attributes called "price-data" and display the total sum inside

<h4 "id="totalDisplay"
using
append()
.

I also need to add an array collection of each checkbox value, which is now 102 and 103. And whole things will be updated as per checkbox selection. I mean h4 display value and array collection value both will be updated in real time as per user checkbox selection. The
valueCollections
variable is for storing array values. I am new to jQuery, that's why I have no idea how to make the total sum and store array values actually. Ask any question you may have. Thanks in advance.



$(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>




Answer Source

You can collect price-data in an array and value on another then if checkbox is checked sum price and show checked checkbox. see below:

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);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h4 id="totalDisplay">
</h4>
<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>

<button class="btn btn-default" id="submitData">Submit</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download