0

It's a simple form which updates the state object onChange and displays that state object when submitted. I was not able to get it to work when there are multiple input elements.

Can anyone tell me what's wrong in this code? onSubmit works when there's only one input element, but not when there are multiple!

class ReactForm extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.validate = this.validate.bind(this);

    this.state = {
      name: "",
      email: ""
    };
  }

  handleChange(event) {
    event.preventDefault();
    const name = event.target.name;
    const value = event.target.value;
    this.setState({
      [name]: value
    });
  }

  validate(event) {
    event.preventDefault();
    console.log(this.state);
  }

  render() {
    return (
      <div>
        <form onSubmit={this.validate}>
          <div>
            <input
              type="text"
              name="name"
              value={this.state.name}
              onChange={this.handleChange}
            />
            <input
              type="email"
              name="email"
              value={this.state.email}
              onChange={this.handleChange}
            />
          </div>
        </form>
      </div>
    );
  }
}

ReactDOM.render(
  <ReactForm />,

  document.getElementById("root")
);

3 Answers 3

2

You need to have a submit button if you have more than 1 input, you can add a hidden one if you want:

<input type="submit" hidden />

Here's a codesandbox: https://codesandbox.io/s/suspicious-almeida-e3f00

And here is the explanation in detail: Why does a FORM with one text INPUT submit on enter while one with two text INPUTs does not?

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

Comments

0

I really liked the approach of tudor.

Here is a different approach that can remove the state handling as well. But this may require polyfill for IE and Safari. You can use FormData to access the form values.

new FormData(e.target);

Here is the working sandbox link: https://codesandbox.io/s/long-wind-ybl1w

Hope this helps!

Comments

0

Please add an element input and button. Button should have type="submit" for submitting!

It will work!

Comments

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.