javascriptreactjstypeaheadbootstrap-typeahead

Calling click() on multiple elements in vanilla js and react


Example: clearButtons has two elements. Problem: clearButton.click() is calling only on the one element. And it should at all

Code here: https://stackblitz.com/edit/react-6bam4e

import {Typeahead} from 'react-bootstrap-typeahead';
 // ES2015

class App extends Component {
  constructor() {
    super();
    this.state = {
      items: [{name: 'A'}, {name: 'B'}]
    };
  }

  clearInput = () => {
    const clearButtons = document.querySelectorAll(".rbt-token-remove-button");  
      for (const clearButton of clearButtons) {   
          clearButton.click();  
      }  
  }

  render() {
    return (
      <div>
         <Typeahead
            id={'example4'}
            defaultSelected={this.state.items.slice(0, 3)}
            /*disabled = {this.state.selectGroupTasksId === ''}*/
            labelKey="name"
            multiple
            options={this.state.items}
            placeholder="Choose ..."
            ref={(ref) => this._typeahead = ref}
          />
          <button onClick={this.clearInput }>Button</button>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

Solution

  • I have no idea what the handler on that button is, but its problematic. Editing your code. This solution worked for me.

      clearInput = () => {
        const clearButtons = document.querySelectorAll(".rbt-token-remove-button");
        if (clearButtons.length > 0) {
          setTimeout(() => {
            clearButtons[0].click();
            this.clearInput()
          })
        }
      }