John John - 5 months ago 16
jQuery Question

Select the price in a jquery array and add to Total

i a have a combo box where i can choose specific vehicle, each has engine size, name and price wrapped in an array.
If vehicle 1 chosen i want to add their price to the total amount.
Here is my code:

HTML

<select id="selector" onChange="Expedisi(this);">
<option>Select product</option>
<optgroup label="Sedan">
<option value="Lancer EX">Lancer EX 1.6 / 2.0</option>
<option value="Lancer EX GT">Lancer EX GT</option>
<optgroup label="Sport">
<option value="Lancer Evolution X">Lancer Evolution X</option>
<optgroup label="SUV">
<option value="Outlander">Outlander</option>
</select>


JavaScript

var data = {
"Lancer EX" : { img: "cars/mitsubishi/lancerex.png" , label: "Lancer EX " , engine: "1.6 L" , price :"16500" },
"Lancer EX GT" : { img: "cars/mitsubishi/gt.png", label: "Lancer EX GT", engine: "2.0 L" , price: "22000"},
"Lancer Evolution X" : { img: "cars/mitsubishi/evox.jpg", label: "Evolution X", engine:"2.0L Turbocharged", price: "85000" },
"Outlander" : { img: "cars/mitsubishi/outlander.jpg", label: "Outlander", engine: "2.0 L" , price : "33000" },
};


I want to add the price of the chosen vehicle from the combo box to the Total which is 0 at first.
Thank you.

Answer

You can access the correct vehicle in your object by using the selected value as the property name. Example:

data[$(this).val()].price

var data = { 
    "Lancer EX" : { img: "cars/mitsubishi/lancerex.png" , label: "Lancer EX " , engine: "1.6 L" , price :"16500" },
    "Lancer EX GT" : { img: "cars/mitsubishi/gt.png", label: "Lancer EX GT", engine: "2.0 L" , price: "22000"},
    "Lancer Evolution X" : { img: "cars/mitsubishi/evox.jpg", label: "Evolution X", engine:"2.0L Turbocharged", price: "85000" },
    "Outlander" : { img: "cars/mitsubishi/outlander.jpg", label: "Outlander", engine: "2.0 L" , price : "33000" },
};

var total = 0;

$('#selector').on('change', function() {
    total = data[$(this).val()].price;
    console.log(total);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<select id="selector">
  <option>Select product</option>
  <optgroup label="Sedan">
  <option value="Lancer EX">Lancer EX 1.6 / 2.0</option>
  <option value="Lancer EX GT">Lancer EX GT</option>
  <optgroup label="Sport">
  <option value="Lancer Evolution X">Lancer Evolution X</option>
  <optgroup label="SUV">
  <option value="Outlander">Outlander</option>
</select>

Comments