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>
);
}
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.
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.
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.
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.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With