-1

I would like to get the "data-price" attribute from the option element onChange. getting the value does work, but i can not get the data-price attribute. I have the following code, which doesnt work.

function getComboA(selectObject) {
  var printit = selectObject.getAttribute("data-price");  
  console.log(printit);
}
/*with this it gets the value tho, but i need the data-price attribute
function getComboA(selectObject) {
  var printit = selectObject.value;  
  console.log(printit);
}

*/
<select id="comboA" onchange="getComboA(this)">
      <option  value="">Select combo</option>
      <option data-price=100 value="Value1">Text1</option>
      <option data-price=200 value="Value2">Text2</option>
      <option data-price=2003 value="Value3">Text3</option>
    </select>

1

3 Answers 3

2

By JavaScript :

var selection = document.getElementById("comboA");
selection.onchange = function(event){
  var printit  = event.target.options[event.target.selectedIndex].dataset.price;
  console.log(printit);
};

Or JQuery :

$('#comboA').change(function(){
      var printit =$(this).find(':selected').attr('data-price')
      console.log(printit);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="comboA" >
      <option  value="">Select combo</option>
      <option data-price=100 value="Value1">Text1</option>
      <option data-price=200 value="Value2">Text2</option>
      <option data-price=2003 value="Value3">Text3</option>
   </select>

Sign up to request clarification or add additional context in comments.

Comments

1

This should make it work:

const comboA = document.querySelector('#comboA');
comboA.addEventListener('change', function(event) {
    console.log(event.target.options[event.target.selectedIndex].dataset.price);
});

With this you can also omit the function call in html.

Comments

0

You can use the selectedIndex of the selectObject to get the index which you can use to get the selected option and then you can get the data-price attribute of that option. Code:

function getComboA(selectObject) {
  var selectedIndex = selectObject.selectedIndex;  
  var selectedPrice = selectObject[selectedIndex].getAttribute("data-price");
  console.log(selectedPrice);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.