1

how to clear data in textbox in reactjs? After submit of the form I want to clear all the data as well as on click of cancel button. Can anyone help please ?

//Create Form
  onSubmit(e){
    e.preventDefault();
      if(this.handleValidation()){
      alert("Form submit");
     }
  }

  //Cancel Form
  onCancel(e){
    e.preventDefault();
    alert("Cancel");
  //  e.target.reset();
}


<button type="submit" className="btn btn-success active" onClick={this.onSubmit}><b>Create</b></button>
<button type="button" className="btn btn-warning"><b>Preview</b></button>
<button type="button" className="btn btn-danger" onClick={this.onCancel}><b>Cancel</b></button>

3 Answers 3

2

Get all input field in state, after reset state with help of setState() function.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.23/browser.min.js"></script>

</head>
<body>
<div id="input"></div>
<script type="text/babel">
    var FormField = React.createClass({
        getInitialState: function(){
            return {
              name:"Vijayabal"
            }
          },
        resetData : function(){
            this.setState({
                name : ''
            });
        },
        render : function(){
            return (
                <div>
                    <input type="text" value = {this.state.name}/>
                    <button onClick = {this.resetData}>Submit</button>
                </div>
            )
        }
    });
    ReactDOM.render(<FormField/>, document.getElementById('input'));
</script>
</body>
</html>
Sign up to request clarification or add additional context in comments.

3 Comments

Cannot read property 'setState' of undefined >>this error I'm getting
Have you set this.state with value name in constructor method?
constructor(props) { super(props); this.state = { fields: {}, errors: {} } this.onSubmit = this.onSubmit.bind(this); }
1

Edited your codesandbox to get it working: https://codesandbox.io/s/m4x7j1jm19

Note that if you set fields to an empty object in your cancel function, then you have to be sure to set each field to an empty string in your input values (I just did the first field):

value={this.state.fields["event_bucket"] || ''}

3 Comments

But yours isn't working. There's an error in your update alert("fields?", fields); where fields isn't defined.
Well, I suppose there's another error for you to debug. If you can't find it then start over with my working example?
You did this: this.state.fields["event_bucket" || ''] instead of what I wrote: this.state.fields["event_bucket"] || ''
0

I recommend making the input a controlled input. Try this on for size:

class ComponentName extends Component {
  constructor(props){
    super(props)
    this.state = {
      myValue: ''
    }

    this.clearData = this.clearData.bind(this)
    this.handleChangeTextbox = this.handleChangeTextbox.bind(this)
    this.onSubmit = this.onSubmit.bind(this)
    this.onCancel = this.onCancel.bind(this)
  }

  clearData(){
    this.setState({
      myValue: ''
    })
  }

  handleValidation(){
    return 'whatever'
  }

  handleChangeTextbox(e){
    this.setState({
      myValue: e.target.value
    })
  }

  onSubmit(e){
    e.preventDefault();
    if(this.handleValidation()){
      alert("Form submit")
      this.clearData()
    }
  }

  onCancel(e){
    e.preventDefault()
    alert("Cancel")
    this.clearData()
  }

  render() {
    return (
      <div>
      <textarea value={this.state.myValue} onChange={this.handleChangeTextbox} />
      <button type="submit" className="btn btn-success active" onClick={this.onSubmit}><b>Create</b></button>
      <button type="button" className="btn btn-warning"><b>Preview</b></button>
      <button type="button" className="btn btn-danger" onClick={this.onCancel}><b>Cancel</b></button>
      </div>
    )
  }
}

See it work here: https://stackblitz.com/edit/so-answer-httpsstackoverflowcomquestions47240386how-to-clear

5 Comments

Consider not using arrow functions and binding the event handlers
The arrow functions part doesn't really affect the answer, I just didn't want to confuse anybody by the way I define class methods.
Why the downvote without a comment? Does this answer in some way not fulfill the question?
Then I suggest following up with comments as to why it won't work rather than downvoting answers that contributors took time out of their day to craft for your own benefit. The answer above works. See this bin: stackblitz.com/edit/react-dkodhj (also, I removed arrow functions in case that confused you)
I changed the name of the bin above. It's now found at: stackblitz.com/edit/…

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.