Matt
Matt

Reputation: 1177

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.

Upvotes: 0

Views: 1112

Answers (2)

Tyler Sebastian
Tyler Sebastian

Reputation: 9448

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

Upvotes: 0

Zach M.
Zach M.

Reputation: 1194

<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.

Upvotes: 1

Related Questions