javascript – How to submit search fields after enter press-ThrowExceptions

Exception or error:

I write my application i React.tsx. I open my menu window which contains many div elemnts with many input fields, checkboxes and select elements. I also have submit button and when i click on it then appears list of results with user’s filters: checks/inputs/selects. I would like to display results also after enter key press. I add this method:

private enterPressed(event: any) {
  const code = event?.keyCode || event?.which;
  if (code === 13) {
    this.onClickSearch();
  }
}

and I also use
onKeyPress={this.enterPressed.bind(this)} to my inputs and selected elements.

I have the following problem. When I open my window and press enter nothing happened. When I focused on any input and then press enter then it works. The solution of this is to set autofocused on any input field but i don’t want to do this in that way. Do you know any other solution, maybe with event listener or something which let me press enter and display results also without any user’s filter and without keeping active any field.?

Thank you in advance for help.

How to solve:

By default, when you wrap you input elements in a <form>, you can submit by pressing enter when focused on a field which is the intended way that forms work.

But since you have mentioned that you do not wish for this behaviour, you can attach an event listener to the window object which will listen to global key presses.

This event listener only needs to be created when the menu is mounted. The listener should be removed when the menu is closed.

class Menu extends Component {
  handleKeyDown = (e) => {
    if (e.keyCode === 13) {
      // enter pressed
    }
  }
  componentDidMount(){
    window.addEventListener("keydown", this.handleKeyDown);
  }
  componentWillUnmount(){
    window.removeEventListener("keydown", this.handleKeyDown);
  }
  //...
}

Leave a Reply

Your email address will not be published. Required fields are marked *