Home > database >  multiinput from submission in react js
multiinput from submission in react js

Time:10-01

I am trying to submit a form in react js I have multiple files

this.state = {
  allValues: [],
};
changeHandler = (e) => {
  this.setState({ ...this.allValues, [e.target.name]: e.target.value });
};

onsubmbit = (e) => {
  e.preventDefault();
  console.log(this.state.allValues);
};
<form onSubmit={this.onsubmbit}>
  <input type='text' name='bloodsugar' onChange={this.changeHandler} value='' />

  <input
    type='text'
    name='bloodpressure'
    onChange={this.changeHandler}
    value=''
  />

  <button type='submit' style={styles.subbtn}>
    Submit
  </button>
</form>;

I am trying to submit a form in react js I have multiple files I am trying to submit this form

console.log(this.state.allValues); when i console log it in submit function i want data as

{
    bloodsugar:data of bloodsugar,
    bloodpressure:data of bloodsugar,
}

when I console log it in submit function I want data like this

CodePudding user response:

You have to set the value of each input field from the state that you set with changeHandler method. Additionally, you need to update the changeHandler method to update the state.allValues as follows.

(Following is the example code I used to test locally. Do the necessary modifications to fit it to your implementation)

import React, { Component } from "react";

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      allValues: {
        bloodsugar: "",
        bloodpressure: "",
      },
    };
  }

  changeHandler = (e) => {
    this.setState({
      allValues: { ...this.state.allValues, [e.target.name]: e.target.value },
    });
  };

  onsubmbit = (e) => {
    e.preventDefault();
    console.log(this.state.allValues);
  };
  render() {
    return (
      <form onSubmit={this.onsubmbit}>
        <div>
          <div style={{ fontSize: "4rem", padding: "15px" }}>
            <i className="fa fa-level-up"></i>
          </div>
          <div style={{ padding: "10px" }}>
            <strong>Enter your blood sugar level</strong>
            <br />
            <input
              type="text"
              name="bloodsugar"
              onChange={this.changeHandler}
              value={this.state.allValues.bloodsugar}
            />
          </div>
        </div>
        <div>
          <div style={{ fontSize: "4rem", padding: "15px" }}>
            <i className="fa fa-area-chart"></i>
          </div>
          <div style={{ padding: "10px" }}>
            <strong>Enter your blood pressure level</strong>
            <br />
            <input
              type="text"
              name="bloodpressure"
              onChange={this.changeHandler}
              value={this.state.allValues.bloodpressure}
            />
          </div>
        </div>

        <button type="submit">Submit</button>
      </form>
    );
  }
}
  • Related