Home > database >  How to stop Enter key press form submitting
How to stop Enter key press form submitting

Time:12-28

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>

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

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>

CodePudding user response:

try this.

const handleSubmit = (data) ={ 
}

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