1

I have an HTML form in my project, which is partially written with React (Don't ask me why. Historical issues.) Consider it to look like this:

<html>
<form>
<input type="text" name="name" />
<div id="app"><!-- React component here --></div>
</form>
</html>

Then the react code, effectively like this:

ReactDOM.render(
  <div>
    <input type="text" />
  </div>,
  app // consider this is the #app element
);

How can I stop the form from submitting with "enter" key by just changing the input element in my React component? Or is it possible?

6
  • I wouldn't expect it to submit on Enter anyway, there's more than one input field in the form. Normally, browsers only submit-on-enter in a text field if the text field is the only field in the form. Commented Apr 3, 2017 at 10:46
  • Working on a component that will dynamically generate text field (behave like textarea). Just want to prevent users from submitting the form by pressing "Enter" in my component. Commented Apr 3, 2017 at 10:47
  • From my experience, "Submit on Enter" works on any text field in the form (even if there are multiple text field). Commented Apr 3, 2017 at 10:48
  • Certainly not mine. For instance, this fiddle with just one input submits if you put your cursor in the field and press Enter, but this one with a secod input does not -- I just tested Chrome, Firefox, and IE11 (the browsers I have handy). Commented Apr 3, 2017 at 10:52
  • 1
    You're right. If your form do not have a submit button, the "Submit on Enter" will be de-activated for multi-field form. But my form do have a submit button. So it is practically this case. :-( Commented Apr 3, 2017 at 11:03

1 Answer 1

2

Put an onKeydown handler on the input accepting the event parameter as e and, in the handler, if e.which is 13, call e.preventDefault to prevent the default action.

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

1 Comment

It works! Thanks! Tried onKeyUp, onKeyPress and it didn't work. onKeyDown do the trick.

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.