开发者

Form calculator using Each() and Children() in jQuery

Im trying to build a form that calculates a total price based on a series of drop down boxes with strin开发者_Python百科g 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>


How about this:

function calculateoptions() {

var total = 0;

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

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

}


You can use:

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

To select each drop down in the product config div.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜