Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve select option data-attribute value in ReactJS?

Tags:

reactjs

I have been trying different ways to retrieve the data-attribute value from a select option. I've tried these but everything comes up null. Any help appreciated.

handleChange(event) { 
    console.log("order by: ", event.target.attributes.getNamedItem('data-order'));
}


render() {

    var options = [];
    this.props.items.map((item) => {
        options.push(<option value={item.value} key={item.label} data-order={item.order}>{item.label}</option>);
     });

    return (
        <div>
            <label>Filter Single Select</label>
            <div>
                <select className="form-control" onChange={this.handleChange} value={this.props.sortBy}>
                    {options}
                </select>
            </div>
        </div>
    );
}
like image 642
bokswagen Avatar asked Feb 03 '16 14:02

bokswagen


People also ask

How do I get the selected option value in React select?

Getting the Selected Value To fetch the selected value from the select element, you can use the onChange event handler prop. Just like the input or textarea elements, you can use the onChange event handler to get the value from the event object.

How do you get the data attribute value in React?

The dataset attribute may not be available in earlier versions of Internet Explorer. In that case, you can use the getAttribute() method. The getAttribute() method will return the string value of the specified attribute. Alternatively, you can also access attributes using the getNamedItem() method.

How do you get the select box value in React?

To set selected value of a select drop down to null with React, we can set the state we use as the value of the value prop of the select drop down to null . to set onChange to a function that calls setSelected to e. target. value which is the selected value if it's truthy.

How do you get selected option text in React JS?

The text of an option is simply the label property of the corresponding item . In your case, to retrieve the text of the selected option, you can do: var selectedItem = this.


1 Answers

Your code is not working because e.target is returning the whole select field and not the individual option. You need to get the index of the selected option and then access that custom attribute. In your change function, this will work:

event.target[event.target.selectedIndex].getAttribute('data-order')
like image 193
Andy Noelker Avatar answered Oct 08 '22 15:10

Andy Noelker