jQuery选择选项值并添加数值并显示结果

时间:2019-06-03 07:39:15

标签: javascript jquery html

我试图选择邮资选项,将小计添加到其中,然后填充div /标签 我已经尝试过这段jQuery代码,将其更改为我的ID,但是没有运气。 我要去哪里错了?

$('#shipping').on('select', function() {
  var shipping = parseFloat($('#shipping').attr("price")) || 0;
  $('#amount').val(shipping + {{$subtotal}});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="d-flex flex-row align-items-center justify-content-start">
  <div class="cart_total_title">Subtotal</div>
  <div class="cart_total_value ml-auto" id="total">£{{$subtotal}}</div>
</li>
<li class="d-flex flex-row align-items-center justify-content-start">
  <div class="cart_total_title">Shipping</div>
  <span></span>
  <select name="shipping" id="shipping" class="" style="width:auto;margin-left:150px;" require="required">
    <option value="" price="4.99">Royal Mail UK Next day delivery: £4.99</option>
    <option value="" price="3.99">Royal Mail Standard delivery: £3.99</option>
  </select>
</li>

3 个答案:

答案 0 :(得分:0)

我认为您要尝试获取的是“运费”选择的值。所以:

var shipping = parseFloat($('#shipping').attr("price")) || 0;

应该是

var shipping = parseFloat($('#shipping').val()) || 0;

选项的值不能为空,应该设置任意值(假设UK_NEXT_DAYSTANDARD_DELIVERY):

<option value="UK_NEXT_DAY" price="4.99">Royal Mail UK Next day delivery: £4.99</option>
<option value="STANDARD_DELIVERY" price="3.99">Royal Mail Standard delivery: £3.99</option>

但是您也可以在价格中填充值,但这对single responsibility principle而言是不明智的做法:

<option value="4.99" price="4.99">Royal Mail UK Next day delivery: £4.99</option>
<option value="3.99" price="3.99">Royal Mail Standard delivery: £3.99</option>

答案 1 :(得分:0)

您可以像这样获得select的attr值:

$(document).ready(function() {
  var shipping = $('#shipping option:selected').attr('price') || 0;
  $('#amount').val(shipping + {{$subtotal}});
});

答案 2 :(得分:0)

下面的代码正常工作,您可以尝试通过下拉菜单更改控制台值。我已经控制台选定的值及其工作。解决方案类似于$('option:selected', this).attr("price")

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
<script>
    $(document).ready(function(){
    $(document).on('change','select#shipping', function() {
        var shipping = parseFloat($('option:selected', this).attr("price"));
        console.log(shipping);
        $('#amount').val(shipping);
    });
    });
</script>
<li class="d-flex flex-row align-items-center justify-content-start">
  <div class="cart_total_title">Subtotal</div>
  <div class="cart_total_value ml-auto" id="total">£{{$subtotal}}</div>
</li>
<li class="d-flex flex-row align-items-center justify-content-start">
  <div class="cart_total_title">Shipping</div>
  <span></span>
  <select name="shipping" id="shipping" class="shipping" style="width:auto;margin-left:150px;" require="required">
    <option value="4.99" price="4.99">Royal Mail UK Next day delivery: £4.99</option>
    <option value="3.99" price="3.99">Royal Mail Standard delivery: £3.99</option>
  </select>
</li>