Reputation: 1171
Is it possible to set data attribute on a select option and if so how I can then get that value onChange
//pseudocode
const getColor = (dcolor) => {
console.log(dcolor)
}
<select onChange={e => getColor(e.target.attributes.data-color)}>
<option value={'red'} data-color={'#FF0000'}>Red</option>
<option value={'green'} data-color={'#00ff00'}>Green</option>
<option value={'blue'} data-color={'#0040ff'}>Blue</option>
<option value={'yellow'} data-color={'#ffff00'}>Yellow</option>
</select>
Upvotes: 1
Views: 1105
Reputation: 367
Not sure if there is anything more simple than that - but you could get the selectedIndex, use that to get the option, and use that to get the color:
onChange=(getColor)
const getColor = (e) => {
const idx = e.target.selectedIndex;
const option = e.target.querySelectorAll('option')[idx];
const color = option.getAttribute('data-color');
return color
}
Upvotes: 2