Get Selected option attribute in React

Aizuddin Badry picture Aizuddin Badry · Apr 5, 2017 · Viewed 10.6k times · Source

I want to get attribute from my select option list.

In meanwhile my code is like below :

I have define option value with "index.name" i want to retrieve "data-id" to get different output. Can someone help me in this ?

EDITED

I have updated my code like below. But still i cannot get the data-id or is there any other method i can get my data id without set "value" with "id".

handleChange(event) {  
    var index = event.target.selectedIndex;
    var optionElement = event.target.childNodes[index]
    var option =  optionElement.getAttribute('data-id');
    this.setState({
    associationsList: option,
    value: event.target.value
    });
  },
   render() {
    var listAssociations = this.state.associations.map(function(index){
        return (
            <option value={index.name} data-id={index.id} ref={index.name} key={index.id}>{index.name}</option>
        )
    });

    var BillingInfo
    {
      if(this.state.associationsList == "0")
      {
        return (   
        <div>
        <Tabs selected={0}>
          <Pane label="Billing Info">
            <div className="row">
                <div className="small-12">
                    Associations:
                    <select value={this.state.value} onChange={this.handleChange}>
                    {listAssociations}
                    </select>
                </div>
            </div>
            <div>
            {this.state.value}<br/>
            {this.state.associationsList}
            Basic package
            </div>
          </Pane>
          <Pane label="Billing History">
            <div>Billing history</div>
          </Pane>
        </Tabs>
      </div>
      );
      }

Answer

squgeim picture squgeim · Apr 5, 2017

You can get the index of the option element that is currently selected in the onChange event in select:

handleChange(e) {
  var index = e.target.selectedIndex;
  var optionElement = e.target.childNodes[index]
  var option =  optionElement.getAttribute('data-id');
  this.setState({
    associationsList: option,
    value: event.target.value
  });
}

This will mean there will be no need to have a onChange handler in the option elements (handleOption).