How to compute the total amount of all selected options' custom "data-price"-attribute values?

37 Views Asked by At

I'm trying to get values from the options of my select-element. It is possible to select any option, and each option features some custom data-* attribute like e.g. ...

<option value="1" data-tokens="1" data-price="500">bbbb</option>

I need to access the value of the data-price attribute which I try as follows ...

let elm = document.getElementById('treatmentCSelect');

elm.addEventListener('change', function (evt) {
  let selectedOption = this.options[this.selectedIndex];
  let price = 0;

  price = sumar(price, parseInt(selectedOption.getAttribute('data-price'), 10));

  console.log(selectedOption);
  // console.log(parseInt(selectedOption.getAttribute('data-price'), 10));
  // console.log(price);
});

But it always does refer just the first option element ...

<option value="1" data-tokens="1" data-price="500">bbbb</option>

My question is, how does one compute the total amount of all selected options' custom data-price-attribute values?

2

There are 2 best solutions below

2
MenTalist On

The problem is that you're trying to retrieve the data-price attribute from the element itself, rather than from the selected element. Try below approach

let e = document.getElementById('treatmentCSelect');
e.addEventListener('change', function(event){
    let selectedOption = e.options[e.selectedIndex];
    let price = parseInt(selectedOption.getAttribute("data-price"));

    console.log(price);
});

1
jagmitg On

Try this: Utilising multiple in the select dropdown.

let e = document.getElementById('treatmentCSelect');

e.addEventListener('change', function() {
    let selectedOptions = e.selectedOptions;
    let totalPrice = 0;
    
    // Loop through all selected options
    for (let option of selectedOptions) {
        totalPrice += parseInt(option.getAttribute('data-price'), 10);
    }
    
    alert(totalPrice);  // Log the accumulated total
});
<select name="treatment" id="treatmentCSelect" multiple>
  <option value="20" data-price="10">Example 1</option>
  <option value="30" data-price="20">Example 2</option>
  <option value="40" data-price="30">Example 3</option>
  <option value="50" data-price="40">Example 4</option>
</select>

EDIT: Agreed - dataset would be a cleaner and efficient way of grabbing values from data attr.

totalPrice += parseInt(option.dataset.price, 10);