从多个选择字段计算总成本值

时间:2015-04-04 15:52:00

标签: jquery

我有以下代码来计算总成本,具体取决于输入到文本字段的内容以及选择了哪个包。

<label for="_mdjm_event_cost" class="mdjm-label">Total Cost:</label>
<br />&pound;
<input type="text" name="_mdjm_event_cost" id="_mdjm_event_cost" class="mdjm-input-currency required" value="" placeholder="0.00" />
<br />
<label for="_mdjm_event_package" class="mdjm-label">Select an Event Package:        </label>
<br />
<select name="_mdjm_event_package" id="_mdjm_event_package">
<option value="" data-price="0.00">No Package</option>
<option value="test" data-price="100.00">Test</option>
</select>
<br />
<label for="_mdjm_event_addons" class="mdjm-label">Select Add-ons:</label>
<br />
<select name="_mdjm_event_addons" id="_mdjm_event_addons" multiple="multiple">
<option value="" disabled="disabled" data-price="0.00">EFFECTS</option>
<option value="" disabled="disabled" data-price="0.00">GENERAL</option>
<option value="" disabled="disabled" data-price="0.00">LIGHTING</option>
<option value="mood-lighting" data-price="50.00">Mood Lighting x 3 - &pound;50.00</option>
</select>

jQuery(document).ready(function ($) {
base = 0;
$("#_mdjm_event_cost").on("keyup", function () {
    base = $('#_mdjm_event_cost').val();
});
$("#_mdjm_event_package").on("change", function () {
    var total = (base * 100 + $(this).find(":selected").data("price") * 100) / 100;
    $("#_mdjm_event_cost").val(total.toFixed(2));
    });
});

在选择包时,代码可以正常计算新的总数。我现在想要扩展它,以便在Add-ons multiple select框中选择(或取消选择)加载项时进一步更新Total Cost字段。

当前工作小提琴https://jsfiddle.net/tanyk8wu/

由于

1 个答案:

答案 0 :(得分:0)

好的我相信我已经通过jQuery代码的以下更新解决了这个问题......

jQuery(document).ready(function ($) {https://jsfiddle.net/tanyk8wu/#collaborate
base = 0;
$("#_mdjm_event_cost").on("keyup", function () {
    base = $('#_mdjm_event_cost').val();
});
$('#_mdjm_event_package, #_mdjm_event_addons').change(function () {
    var extras = 0;
    var packages = 0;
    var addons = 0;
    $('#_mdjm_event_package :selected').each(function () {
        packages += Number($(this).data("price"));
    });
    $('#_mdjm_event_addons :selected').each(function () {
        addons += Number($(this).data("price"));
    });
    var extras = ( packages + addons );
    var total = (base * 100 + extras * 100) / 100;
    if (total == "0") {
        $("#_mdjm_event_cost").val('');
    } else {
        $("#_mdjm_event_cost").val(total.toFixed(2));
    }
});
});

似乎工作。 在https://jsfiddle.net/tanyk8wu/5/

进行演示