1

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>
1

1 Answer 1

2

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    
}
Sign up to request clarification or add additional context in comments.

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.