views:

316

answers:

2

Im trying to build a form that calculates a total price based on a series of drop down boxes with string values such as "This option costs £30" i know this is not ideal but im putting this together as a hack for an existing script

For the most part ive got it working however im not sure how to run the each function for each child of #productconfig

I can manually input each of the drop downs ids into an array and that makes the calculation but it would be good if it just worked 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>
A: 

You can use:

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

To select each drop down in the product config div.

Vincent Ramdhanie
+2  A: 

How about this:

function calculateoptions() {

var total = 0;

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

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

}
Greg
thanks greg, this works with my old code in the function.<code> total += $(this).val().match(/£(\d+)/)[1];</code>this doesnt seem to work however. i think its adding the values as strings not numerically. the output is £050000000060010000
James