简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM