well, have text input gets sum of attributes of "price" inside checkboxes checked. can't attribute value checkbox.
here function:
function sum_options() { var options = []; $("#form-field-1-11-1").attr("price", 500); $("#form-field-1-11-2").attr("price", 500); $("#form-field-1-11-3").attr("price", 0); $("#form-field-1-11-4").attr("price", 300); $("#form-field-1-11-5").attr("price", 500); $("#form-field-1-11-6").attr("price", 500); $("#form-field-1-11-7").attr("price", 1250); $("#form-field-1-11-8").attr("price", 500); $("#form-field-1-11-9").attr("price", 700); options[0] = $("#form-field-1-11-1"); options[1] = $("#form-field-1-11-2"); options[2] = $("#form-field-1-11-3"); options[3] = $("#form-field-1-11-4"); options[4] = $("#form-field-1-11-5"); options[5] = $("#form-field-1-11-6"); options[6] = $("#form-field-1-11-7"); options[7] = $("#form-field-1-11-8"); options[8] = $("#form-field-1-11-9"); var total = 0; $.each(options, function() { this.on("change", function() { total += this.attr("price"); }); }); $("#sum-field").val(total); }
thanks!!!
your code lot more complex needs be.
firstly, should use data-*
attributes assign custom data element. creating own non-standard attributes mean html invalid , can lead other issues. also, if code relying on price
attribute, should in dom when page loads.
secondly there's no need build array of single elements. can select them in single jquery object , set change()
event handler on them in single call. grouped them class
in below example.
lastly can total of prices looping through :checked
boxes , adding prices. try this:
$('.checkbox').change(function() { var total = 0; $('.checkbox:checked').each(function() { total += parsefloat($(this).data('price')); }); $("#sum-field").val(total); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="checkbox" id="form-field-1-11-1" class="checkbox" data-price="500" /> <input type="checkbox" id="form-field-1-11-2" class="checkbox" data-price="500" /> <input type="checkbox" id="form-field-1-11-3" class="checkbox" data-price="0" /> <input type="checkbox" id="form-field-1-11-4" class="checkbox" data-price="300" /> <!-- other checkboxes here... --> <input type="text" id="sum-field" />