skip to Main Content

I´m traying to get values from my selectpicker. i can select any options and this options have personaliced attr:

<option value="{{ $treatment->id }}" data-tokens="{{ $treatment->id }}" data-price="{{ $treatment->session_price }}">{{ $treatment->treatment_name }}</option>

i need get data-price to do this, i´m doing:

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

                    console.log(e.options[e.selectedIndex]);


                    //console.log(parseInt(e.options[e.selectedIndex]));
                });

But always return first option (console.log result):

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

My question it´s. How i can to do to amount data-price when i select options?

2

Answers


  1. 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);
    });
    
    
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search