Form calculator using the Everyone () and Children () functions in jQuery

I am trying to create a form that calculates the total price based on a series of dropdown boxes with string values ​​like "This option costs £ 30", I know this is not ideal, but I am putting together this as a hack to an existing script

For the most part I got it working, but not sure how to run each function on each child of #productconfig

I can manually enter each of the drop downs ids into the array and that does the calculation, but it would be nice if it just works with all the children of #productconfig

<code>

<div id="#productconfig">
<label>Model Type</label> 
<select name="products[220][data][modeltype]" id="data-modeltype-220">
    <option value="M-Type £500">M-Type £500</option>
    <option value="P-Type £500">P-Type £500</option>
    <option value="S-Type £500">S-Type £500</option>
</select>   
</div>
</code>

<code>
$(document).ready(function() {
$("#productconfig").children().change(function () {
    calculateoptions();
});
calculateoptions();
});
</code>
<code>
function calculateoptions() {

var arr = ["data-modeltype-220"];

var total = 0;

jQuery.each(arr, function () {
    var str = $('#' + this).attr("value");
    var poundsign = str.indexOf('£');
    var poundsign = poundsign + 1;
    var lengthofstr = str.length;
    var shortstr = str.substr(poundsign, lengthofstr);
    total = eval(total) + eval(shortstr);
});

$('#price').html("£" + total);

}
</code>

      

+2


source to share


2 answers


How about this:



function calculateoptions() {

var total = 0;

jQuery('#productconfig select').each(function () {
        total += $(this).val().match(/£(\d+)/)[1];
});

$('#price').html("£" + total);

}

      

+2


source


You can use:

 $("#productconfig select").each(function(){...});

      



To select each snapshot in the product configuration dialog.

0


source







All Articles