aBloomer aBloomer - 1 month ago 8
Javascript Question

How should i get the value from custom attribute in react element?

Below is my html looks like.....

<select onclick={this.handleClick}>
<option key="1" value="aaa" data-plan-id="test"></option>
</select>


Below is my handleClick event code

console.log(e.target.value); // this will output aaa


My question is how can I get the value from "data-plan-id" attribute which is "test"??

Answer

Just read selectedOptions HTMLCollection and take the first option from it:

console.log(e.target.selectedOptions[0].getAttribute('data-plan-id'));

With modern browsers (IE11+, see support) you can use dataset interface instead of getAttribute:

console.log(e.target.selectedOptions[0].dataset.planId);
Comments