1

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);
1
  • your code is working as I tested it. Both value and text are changed. Commented Dec 7, 2018 at 10:37

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

5 Comments

It would help, but form is written in pure JS and I don't have access to it. I have to handle it by pure JS then or at least jQuery.
Ah ok, so you have a react app, and within that is a form which is not written in react?
Yes, there's a widget form out of the project. All the rest is in react.
I've tried this out but I can't seem to get any error; the code you have works. Are you able to provide any more detail?
Okay. I'll tell you what I get in steps 1. Page loading 2. Form widget loading 3. Timeout trigger 4. Select option change But text is still the same. It doesn't show text of current option. It shows only default text.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.