从jquery中的所选选项计算价格

时间:2015-04-23 05:05:27

标签: javascript jquery html

我的HTML代码:

<select class="form-control B3 pricing" name="B3">
  <option data-price="0" data-cheap="0">0</option>
  <option data-price="20" data-cheap="30">1</option>
  <option data-price="40" data-cheap="60">2</option>        
  <option data-price="60" data-cheap="90">3</option>
  <option data-price="80" data-cheap="120">4</option>
  <option data-price="100" data-cheap="150">5</option>
</select>

我的jquery代码:

$(document).ready(function () {
            var cheap=false;
        $('.day1').on('change', function (e) {
            var optionSelected = $("option:selected", this);
            var valueSelected = optionSelected.val();
            if(valueSelected=="Saturday")
            {
                cheap=true;
                alert(cheap);                   
            }else{
                cheap=false;
                alert(cheap);
            }
        });
    $('.pricing').change(function(){
        var price = parseFloat($('.total').data('base-price'));
        $('.pricing').each(function(i, el) {
                if(cheap==false){
                    price += parseFloat($('option:selected', el).data('price'));
                }else{
                    price+= parseFloat($('option:selected').data('cheap'));
                }
        });            
        $('.total').val('$'+price.toFixed(2));
    }); 
});

我希望当选择星期六作为星期六时,必须采取数据便宜,并且当选择其他日期时,应计算数据价格。有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

我唯一能看到的问题是你没有将上下文传递给廉价查询

$(document).ready(function () {
    var cheap = false;
    $('.day1').on('change', function (e) {
        cheap = $(this).val() == "Saturday";
    });
    $('.pricing').change(function () {
        var price = parseFloat($('.total').data('base-price')) || 0;
        $('.pricing').each(function (i, el) {
            price += parseFloat($('option:selected', el).data(cheap ? 'cheap' : 'price'));
            console.log('x', price)
            $('.total').val('$' + price.toFixed(2));
        });
    });
});

演示:Fiddle