Tanvir Ahmed
Tanvir Ahmed

Reputation: 3

How to stop Enter key press form submitting

I want to press enter key so that the form is not submitted, just click on the submit button and the form will be submitted in ReactJS

const handleSubmit = (data) ={ 
}

<form onSubmit={handleSubmit}>
  <label>
    Name:
    <input type="text" name="name" />
  </label>
  <input type="submit" value="Submit" />
</form>

Upvotes: 0

Views: 67

Answers (3)

Peppermintology
Peppermintology

Reputation: 10220

What you can do is apply an onKeyPress handler to your form and if the value of the key that has been pressed is Enter, prevent the default behaviour (submit).

<form
  onSubmit={handleSubmit}
  onKeyPress={(e) => {
    e.key === "Enter" && e.preventDefault();
  }}
>
  <label>
    Name:
    <input type="text" name="name" />
  </label>
  <button type="submit">Submit</button>
</form>

Note that you will likely also want to prevent the default for behaviour when your form is submitted, otherwise you'll likely get a page refresh.

const handleSubmit = (event) => {
  event.preventDefault();
}

To get the value of your name input, you would do the following:

const handleSubmit = (event) => {
  event.preventDefault();

  console.log(event.target.name.value);
}

The same principle applies for any other fields you might have in the form.

Functioning CodeSandbox example.

Upvotes: 0

Farnam H
Farnam H

Reputation: 190

You can change your handleSubmit function like this:

const handleSubmit = (e) => {
    e.preventDefault()
 }

e.preventDefault() this prevent the default behaviour of the form and all the events related to that.

Upvotes: 0

Arman Kazi
Arman Kazi

Reputation: 189

You can do this without using a form tag and store the input values in a state

const handleSubmit = () ={


}


<div>
  <div>
    Name:
  <input type="text" name="name" />
  </div>
  <input onClick={handleSubmit} value="Submit" />
</div>

Upvotes: -2

Related Questions