veronica veronica - 2 months ago 8
HTML Question

Set price using selection from dropdown menu

How can I set the price of items using

dropdown
menu lets say I have a dropdown menu with cars and trucks and depending on what the user picks the prices will vary how can I set the price of each one and update a box containing the price of each item.



<p><b>Truck: &nbsp;&nbsp;&nbsp;</b><select id="states" name="states" size="1">
<option>Please Choose</option>
<option value="F150">F150</option>
<option value="Ram1500">Ram1500</option>
<option value="chevy">chevy</option>

</select><br /></p><p><b>sports car: &nbsp;&nbsp;&nbsp;</b><select id="states" name="states" size="1">
<option>Please Choose</option>
<option value="mustang">mustang</option>
<option value="charger">charger</option>
<option value="camaro">camaro</option>

</select><br /></p>




Answer

Add extra attribute for price uzing data-* attributes, then on change get the value of this attribute and show it in the price field :

$('body').on('change', '#trucks', function(){
  var selected_truck_price = $('option:selected', this).data('price');
  
  $('#price').val(selected_truck_price);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <b>Truck: &nbsp;&nbsp;&nbsp;</b>
  <select id="trucks" name="trucks" size="1">
    <option>Please Choose</option>
    <option data-price="150" value="F150">F150</option>
    <option data-price="1500" value="Ram1500">Ram1500</option>
    <option data-price="2000" value="chevy">chevy</option>
  </select>
  <br/>
</p>

Price : <input name='price' id='price'/>

Hope this helps.