user1008636
user1008636

Reputation: 3181

Confused about OnSubmit

I have:

<form onSubmit= {handleSubmit}>
      <div className="form-group">
        <label htmlFor="focusedInput">Level</label>
        <input className="form-control" id="focusedInput" type="number" />               
        <div className="input-group-append">
          <button className="btn " type="submit">Submit</button>
        </div>
      </div>
      </form>

in my handleSubmit, how do I pass in the value in my form-control (type="number") into a props function? event.target.value doesn't seem to work.

Upvotes: 0

Views: 71

Answers (2)

Sameer Reza Khan
Sameer Reza Khan

Reputation: 464

You need to use state for controlled input.

example:

this.state={
    number :0 //initialise state variable here or in componentWillMount or componentDidMount
}

handleChange(e){
// input change handler,extract value from e, update state here.
this.setState({
    number: e.target.value
})

handleSubmit(){
    // Use state variable and make ajax call or anything you want with your input here.
}

Your input form will look like this.

<input className="form-control" id="focusedInput" type="number" value={this.state.number} onChange={this.handleChange.bind(this)/> 
//you can bind your function in constructor too.

Your submit button will look like this

<button className="btn " onClick={this.handleSubmit.bind(this)>Submit</button>

bind(this) is important, you need to bind your function in constructor or same as mentioned above. when you bind it in constructor, you don't need to write bind(this) in input and button

Upvotes: 1

Maksim Romanenko
Maksim Romanenko

Reputation: 365

There are few way to address it:

  1. Save values into state onChange event. Good examples in docs https://reactjs.org/docs/forms.html.

  2. Define ref and read value on submit. https://reactjs.org/docs/refs-and-the-dom.html

Upvotes: 0

Related Questions