1

I am having a input in react component, When the input is inside , Enter button will trigger a click, but if input is not wrapped inside form, Enter does not work,

Is wrapping input by form the only way to activate Enter button ?

    <div>
        <input name=“name” type="text"
           value={somevalue} onChange={this.handleChange}/>
        <button  id=“searchbutton”
            onClick={this.handleSubmit}>
            {search label}
        </button>
    </div>
5
  • This is the default behavior of HTML. You could also prevent this behavior and manually bind the keyup event to a method. Commented Jul 31, 2019 at 7:18
  • 1
    is there a reason you don't want to use form? Commented Jul 31, 2019 at 7:18
  • Check this - stackoverflow.com/questions/27827234/… Commented Jul 31, 2019 at 7:26
  • Just to be clear: You want the Enter key in the input to trigger the button, right? Commented Jul 31, 2019 at 7:26
  • 1
    thats correct @T.J.Crowder Commented Jul 31, 2019 at 9:01

2 Answers 2

2

Is wrapping input by form the only way to activate Enter button ?

Your other option is to use a keypress handler on the input and check for the Enter key.

The reason it works when this is in a form is that browsers automatically click the submit button on a form if the form has only a single text input and the user presses Enter. Without the form, you don't get that automatic behavior.

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

2 Comments

This is exactly what I had to do with an input that I had created outside of a form. I had to create a separate keypress handler for it to handle the user pressing the enter key. This, for me, is the best solution to this if for some reason you don't want to use a form.
@OsamaKhalid - Right, which is why the OP sees the behavior he sees when this is in a form. I'm not sure why the comment...?
0
//By default in form type of button is "submit". Change that to : 
    <button  type="button" id="searchbutton"
           onClick={this.handleSubmit}>
           {search label}
    </button>

3 Comments

My impression is that the OP wants the Enter key (in the input) to click the button. Changing it to a plain button will stop that.
He is calling the function on click, so it will work, from where ever it is clicked!
The OP has now confirmed that he wants pressing Enter in the input to click the button.

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.