Reputation: 11
I have a problem with select in JavaScript. I'd like to change option of select. The option is changing, but text is default. Why is that? What can I change in my code? I need timeout, because script is loading slowly.
setTimeout(() => {
if(this.props.Locale === "en-EN") {
let country = document.getElementById("Country");
country.getElementsByTagName("option")[10].selected = "selected";
}
}, 3000);
Upvotes: 1
Views: 56
Reputation: 6466
You can control the selected option using the value
property of the select
component. You can bind it to an item in state and then set that to whatever you need. I've given an example below, which isn't particularly great code, but gives a demonstration of how this might work:
class App extends React.Component {
state = {
selectedOption: 2,
}
updateSelectedOption(newValue) {
this.setState({
selectedOption: newValue
});
}
render() {
return (
<div>
<select
onChange={({ target }) => { this.updateSelectedOption(target.value) }}
value={this.state.selectedOption}
>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<button onClick={() => this.updateSelectedOption(1)}>1</button>
<button onClick={() => this.updateSelectedOption(5)}>5</button>
</div>
)
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
Upvotes: 1