简体   繁体   English

用数量计算价格

[英]Calculate price with amount of quantity

I have a web page for employees where they can choose an item from a dropdown and it will automatically input the price of that item for them. 我有一个面向员工的网页,他们可以从下拉菜单中选择一个项目,它将自动为他们输入该项目的价格。 Here is my code: 这是我的代码:

<script>
$(document).ready(function() {

  $('#price_input').on('change', function() {
    $selection = $(this).find(':selected');
    $('#opt_value').val($selection.val());
    $('#opt_price').val($selection.data('price'));
  });
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="price_input">
  <option value="Coffee" data-price="3.00">Coffee</option>
  <option value="Chips" data-price="0.75">Chips</option>
  <option value="Soda" data-price="2.50">Soda</option>
</select>
<div>Option Value <input type="text" id="opt_value"/></div>
<div>Option Price <input type="text" id="opt_price"/></div>

The code works properly, but how would I be able to add a quantity input that defaults to 1 and when it is changed to two, the price doubles, and when it is changed to three the price triples in the "Option Price" input for example. 该代码正常工作,但是我如何能够添加默认为1的数量输入,当其更改为2时,价格翻倍,而当其更改为3时,价格输入为“三倍”例。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {

  $('#price_input').on('change', function() {
    $selection = $(this).find(':selected');
    $('#opt_value').val($selection.val());
    $('#opt_price').val($selection.data('price'));
    $('#quantity_input').on('change', function() {
        $('#opt_price').val($selection.data('price') * $(this).val());
    });
  });
});
</script>

<select id="price_input">
  <option value="Coffee" data-price="3.00">Coffee</option>
  <option value="Chips" data-price="0.75">Chips</option>
  <option value="Soda" data-price="2.50">Soda</option>
</select>
<select id="quantity_input">
  <option value="1" >1</option>
  <option value="2" >2</option>
  <option value="3" >3</option>
</select>
<div>Option Value <input type="text" id="opt_value"/></div>
<div>Option Price <input type="text" id="opt_price"/></div>

Calculation works on change, as for default values and monitoring both you can figure that part out. 计算会根据更改进行,因为默认值和监视都可以弄清楚该部分。 on change for the quantity dropdown functions so that should get you started. 更改数量下拉菜单功能,以便您入门。

var select = $("#opt");
var price = $("input#opt_price");
var quantity = $("input#opt_quantity");

var onChangeSelect = function() {
    price.val(select.children(":selected").data('price'));
    quantity.val(1);
}

select.on('change', onChangeSelect);
quantity.on('change', function() {
    price.val(select.children(':selected').data('price') * $(this).val());
});

onChangeSelect();

updated 更新

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM