Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React onSubmit event not working

When I hit enter on the form, it does not trigger the onSubmit event. There are no errors. The other event, onBlur, does dispatch. The logForm function will eventually console.log a JSON string of all the form's fields, but I have not yet gotten that far. I am simply trying to trigger the onSubmit event on the form. Any help or explanation would be appreciated. Here's the code:

import React from 'react'

export default function SignupForm() {
  return (
    <form onSubmit={logForm}>
      <div className="form-group">
        <label>
          Name:
          <input onBlur={logUpdate} className="form-control" 
          type="text" placeholder="Username"/>
        </label>
      </div>
      <div className="form-group">
        <label>
          Email:
          <input onBlur={logUpdate} className="form-control" 
          type="text" placeholder="[email protected]"/>
        </label>
      </div>
      <div className="form-group">
        <label>
          Password:
          <input onBlur={logUpdate} className="form-control" 
          type="password" placeholder="Password"/>
        </label>
      </div>
      <div className="form-group">
        <label>
          Confirm Password:
          <input onBlur={logUpdate} className="form-control" 
          type="password" placeholder="Password"/>
        </label>
      </div>
    </form>
  )
}

function logForm(e) {
  e.preventDefault()
  const formInfo = new FormData(e.target)
  console.log(formInfo)
}

function logUpdate(e) {
  console.log(e.target.value)
}
like image 574
Nic Bonetto Avatar asked Jan 01 '26 02:01

Nic Bonetto


1 Answers

What you can do is put an onKeyPressed event on your form controls like so

onKeyPress={this.onKeyPressed}

and then have a function catching the onKeyPressed

onKeyPressed: function (e) {
    if (e.key === "Enter") {
        logForm(e);
    }
}

If you want Submit to work, add a button to your html section: (Credit to @TryingToImprove)

  <div className="form-group">
    <label>
      <button className="btn btn-default" type="submit">submit form</button>
    </label>
  </div>
like image 186
Tikkes Avatar answered Jan 03 '26 15:01

Tikkes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!