Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the label of dropdown in react?

I want to get the label of a dropdown list (Eg:Inventory Part,Non-Inventory Part ..) from the dropdownlist The code for dropdown list is

<select value={'ItemType'}  onChange={this.handleChange}  style={{'width':'448px'}}>
                     <option value='0'>Select An Item Type</option>
                     <option value='1'>**Inventory Part**</option>
                     <option value='2'>**Non-Inventory Part**</option> 
                     <option value='3'>Other Change</option>
                     <option value='4'>Subtotal</option>
                     <option value='5'>Group</option> 
                     <option value='6'>Discount</option> 
                     <option value='7'>Payment</option>
                     <option value='8'>Sales Tax Item</option>
                     <option value='9'>Sales Tax Group</option>
                    </select>

The handleChange function and constructor is as follows:

constructor(props){
    super(props);
    this.state={type:''}
  }
handleChange = (e) => {
    this.setState({type:e.target.value});
  };

How can I modify my handleChange so that I get the labels of the options?

like image 224
Jane Fred Avatar asked Nov 26 '25 23:11

Jane Fred


2 Answers

Adding a new state 'label' holding the label

constructor(props){
    super(props);
    this.state={type:'', label: ''}
}      
handleChange = (e) => {
    let index = e.nativeEvent.target.selectedIndex;
    let label = e.nativeEvent.target[index].text;
    let value = e.target.value;
    this.setState({ type: value, label: label});
}
like image 52
Pengcheng Avatar answered Nov 28 '25 14:11

Pengcheng


You can use this

var index = e.nativeEvent.target.selectedIndex;
var text =e.nativeEvent.target[index].text;
console.log(text);

Your handle change method

handleChange = (e) => {

   var index = e.nativeEvent.target.selectedIndex;
  var text =e.nativeEvent.target[index].text;
console.log(text);
    this.setState({type:e.target.value});

  };

Here is the demo of it: https://stackblitz.com/edit/react-ymwpeu

like image 26
Just code Avatar answered Nov 28 '25 14:11

Just code