I'd like to add a data value to an option tag in a select element. For example data-price
but my problem is that I have multiple select tags. So how do I get JavaScript to grab the data value of that option that the user selects?
How I want it to work:
Select element #1 contains:
<select onchange="updatePrice()">
<option data-price="1">Apple $1</option>
<option data-price="2">Potato $2</option>
<option data-price="3">Bag of Grapes $3</option>
</select>
Select element #2 contains:
<select onchange="updatePrice()">
<option data-price="5">Really good cake</option>
<option data-price="15">Super Good Cake</option>
</select>
Then I'm honestly not sure what to do in the JS... But I want it to grab what the user selected, get the data-price
then calculate the total (just by adding select1 + select2).
EDIT: My answer is different than this question because my question is more specific and requires different methods. Even though this is specific it could help a developer in the future by the answers it gets. Therefore it is not a duplicate but a more specific question than the other. Though that question has a simpler answer that could be plugged in if the developer knows how to.
This is a bit tricky. You need to give an identifier so our code won't get confused.
<select id="goods1" onchange="updatePrice(this)">
<option data-price="0">Select one</option>
<option data-price="1">Apple $1</option>
<option data-price="2">Potato $2</option>
<option data-price="3">Bag of Grapes $3</option>
</select>
<select id="goods2" onchange="updatePrice(this)">
<option data-price="0">Select one</option>
<option data-price="5">Really good cake</option>
<option data-price="15">Super Good Cake</option>
</select>
First, add a global variable to storing current price. Second, store the identifier and the price value. Finally, manipulate the current price.
<script>
let price = 0;
let stored = {};
const updatePrice = elm => {
const id = elm.id;
const selectedPrice = parseInt(
Array.from(
elm.children
).filter(x => x.selected)[0].dataset.price
);
price = 0;
stored[id] = selectedPrice;
Object.keys(stored).forEach(key => price += stored[key]);
console.log(`Price: ${price}`);
};
</script>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments