Krishna
Krishna

Reputation: 1209

How to get the attribute of an option

I have create a dynamic dropdown using JS

var str = `<select onchange="getPrice(this)"><option value="">Select</option>`;
for(var s=0;s<arr.length;s++) {
    str += `<option value="${arr[i].name}" price="${arr[i].price}">${arr[i].name}</option>`;
}
str += '</select>

function getPrice(ele) { 
    console.log(ele.value); //getting the value here
    console.log(ele.price); //getting null here 
}

ele.price is giving me null

Upvotes: 0

Views: 40

Answers (1)

Satpal
Satpal

Reputation: 133403

You can first get the reference of selected option then use getAttribute()

ele.options[ele.selectedIndex].getAttribute('price')

However, I would recommend you to use data-* prefixed attribute

<option value="${arr[i].name}" data-price="${arr[i].price}">${arr[i].name}</option>

then Element.dataset property can be used.

var price = ele.options[ele.selectedIndex].dataset.price

Upvotes: 1

Related Questions