Home > Enterprise >  onChange is not invoked when dropdown menu has only 1 item
onChange is not invoked when dropdown menu has only 1 item

Time:12-25

I am populating my dropdown menu dynamically and I sometimes end up with having a single element in the dropdown. For multiple elements, there is no problem, the onChange() of my select tag works perfect. However, when there is only 1 element, the onChange() does not invoke. How can I solve this problem? Thank you!

getOptions(){
    var dynamicOptions = this.props.something
    const returnedOptions = []
    for(int i=0; i< dynamicOptions.length;i  ){
          returnedOptions.push(<option value = {dynamicOptions[i]}>something</option>
    }
    return dynamicOptions;
}

return(
    <select onChange=this.onchangemethod, value = {something}>
    {this.getOptions()}
    </select>
)

CodePudding user response:

You would be having the same problem if the user would like to select the first option of many, since it would be the already selected one and the user would not need to re-select it.

One workaround is to always specify an "empty" option with a placeholder text

<select onChange={this.onchangemethod}>
  <option value="">Please choose an option</option>
  {this.getOptions()}
</select>

This way, you will always have at least two options, and the user will have to open and select one.


An alternative is to pre-select the first option so that, again, in case of user inaction, there is one option selected.

for(int i=0; i < dynamicOptions.length; i  ) {
  const optionProperties = {value: dynamicOptions[i]};
  if (i === 0) { optionProperties.selected: true };
  returnedOptions.push(<option {...optionProperties}>something</option>);
}
  • Related