2

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"??

2 Answers 2

7

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

1 Comment

Appreciate for help.
1

You need to loop through all the <option> of the <select> and check if the value are same. If yes, check for dataset. This will have plan-id.

Ps. Javascript will convert dashed data attribute to camelCase plan-id -> planId

Hope this helps!

class App extends React.Component{
  constructor(){
    super()
    this.onChange = this.onChange.bind(this)
    this.state = {
      component: 'A'
    }
  }
  onChange(e){
    [...e.target.childNodes].forEach((el) => { //convert HTML collection to array
      if(el.value === e.target.value) 
        console.log(el.dataset.planId)
    })
    this.setState({
      component: e.target.value
    })
  }
  
  render(){
    return <div>
      <select onChange={this.onChange} selected={this.state.component}>
        <option value="aaa" data-plan-id="a plan">A</option>
        <option value="bbb" data-plan-id="b plan">B</option>
      </select>
    </div>
  }
}
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>

1 Comment

Sorry for typo,, I did put onClick event in select tag and what i want is to get data-plan-id vlaue

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.