Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clear and reset form input fields

Tags:

reactjs

I have a form containing various input fields and two buttons; one for submitting and one for cancelling.

<form id="create-course-form">   <input type="text" name="course_Name" ref="fieldName">   <input type="text" name="course_org" ref="fieldOrg">   <input type="text" name="course_Number" ref="fieldNum">    <input type="submit" name="saveCourse" value="Create">   <input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse}> </form> 

What I want is to empty all inputs when the cancel button is clicked. So far I've managed to do this by using each input's ref prop.

cancelCourse(){   this.refs.fieldName.value="";   this.refs.fieldorg.value="";   this.refs.fieldNum.value=""; } 

However, I want to empty the input fields without having to empty each one seperately. I want something similar to this (jQuery): $('#create-course-form input[type=text]').val('');

like image 538
ChemseddineZ Avatar asked May 11 '17 17:05

ChemseddineZ


People also ask

How do you reset input field in form?

To clear all the input in an HTML form, use the <input> tag with the type attribute as reset.

How do I reset form fields in React?

The solution is to use the reset() function from the React Hook Form library, if you execute the function without any parameters ( reset() ) the form is reset to its default values, if you pass an object to the function it will set the form with the values from the object (e.g. reset({ firstName: 'Bob' }) ).

How do you clear input field after submit in React?

To clear input values after form submit in React: Store the values of the input fields in state variables. Set the onSubmit prop on the form element. When the submit button is clicked, set the state variables to empty strings.

How do you reset fields in HTML?

The <input type="reset"> defines a reset button which resets all form values to its initial values.


1 Answers

The answer here depends on whether or not your inputs are controlled or uncontrolled. If you are unsure or need more info on this, check out what the official docs say about controlled components and uncontrolled components. Thanks @Dan-Esparza for providing the links.

Also, please note that using string literals in ref is deprecated. Use the standard callback method instead.


Clearing a form with uncontrolled fields

You can clear the entire form rather than each form field individually.

cancelCourse = () => {    document.getElementById("create-course-form").reset(); }  render() {   return (     <form id="create-course-form">       <input />       <input />       ...       <input />     </form>   ); } 

If your form didn't have an id attribute you could use a ref as well:

cancelCourse = () => {    this.myFormRef.reset(); }  render() {   return (     <form ref={(el) => this.myFormRef = el;}>       <input />       <input />       ...       <input />     </form>   ); } 

Clearing a form with controlled fields

If you are using controlled form fields, you may have to explicitly reset each component inside your form, depending on how your values are stored in the state.

If they are declared individually, you need to reset each one explicitly:

cancelCourse = () => {    this.setState({     inputVal_1: "",     inputVal_2: "",     ...     inputVal_n: "",   }); }  render() {   return (     <input value={this.state.inputVal_1} onChange={this.handleInput1Change}>     <input value={this.state.inputVal_2} onChange={this.handleInput2Change}>     ...     <input value={this.state.inputVal_n} onChange={this.handleInputnChange}>   ); } 

Demo below:

class MyApp extends React.Component {   constructor() {     super();     this.state = {       inputVal_1: "",       inputVal_2: "",       inputVal_3: "",       inputVal_4: "",       inputVal_5: "",       inputVal_6: "",       inputVal_7: "",       inputVal_8: "",       inputVal_9: "",       inputVal_10: ""     };   }      handleInput1Change = (e) => {     this.setState({inputVal_1: e.target.value});   }      handleInput2Change = (e) => {     this.setState({inputVal_2: e.target.value});   }      handleInput3Change = (e) => {     this.setState({inputVal_3: e.target.value});   }      handleInput4Change = (e) => {     this.setState({inputVal_4: e.target.value});   }      handleInput5Change = (e) => {     this.setState({inputVal_5: e.target.value});   }      handleInput6Change = (e) => {     this.setState({inputVal_6: e.target.value});   }      handleInput7Change = (e) => {     this.setState({inputVal_7: e.target.value});   }      handleInput8Change = (e) => {     this.setState({inputVal_8: e.target.value});   }      handleInput9Change = (e) => {     this.setState({inputVal_9: e.target.value});   }      handleInput10Change = (e) => {     this.setState({inputVal_10: e.target.value});   }      cancelCourse = () => {      this.setState({       inputVal_1: "",       inputVal_2: "",       inputVal_3: "",       inputVal_4: "",       inputVal_5: "",       inputVal_6: "",       inputVal_7: "",       inputVal_8: "",       inputVal_9: "",       inputVal_10: ""     });   }      render() {     return (       <form>         <input value={this.state.inputVal_1} onChange={this.handleInput1Change} />         <input value={this.state.inputVal_2} onChange={this.handleInput2Change} />         <input value={this.state.inputVal_3} onChange={this.handleInput3Change} />         <input value={this.state.inputVal_4} onChange={this.handleInput4Change} />         <input value={this.state.inputVal_5} onChange={this.handleInput5Change} />         <input value={this.state.inputVal_6} onChange={this.handleInput6Change} />         <input value={this.state.inputVal_7} onChange={this.handleInput7Change} />         <input value={this.state.inputVal_8} onChange={this.handleInput8Change} />         <input value={this.state.inputVal_9} onChange={this.handleInput9Change} />         <input value={this.state.inputVal_10} onChange={this.handleInput10Change} />         <input type="submit" name="saveCourse" value="Create" />         <input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />       </form>     );   } }  ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div>

There is a cleaner way to do this though. Rather than having n state properties and n event handlers, one for each input, with some clever coding we can reduce the code dramatically.

In the constructor we just declare an empty object, which will be used to hold input values. We use only one input handler and pass it the index of the input element we want to change the value of. This means that the value of an individual input is generated the moment we start typing into it.

To reset the form, we only need to set our input object back to being empty again.

The input value is this.state.inputVal[i]. If i doesn't exist (we haven't typed anything yet into that input) we want the value to be an empty string (instead of null).

cancelCourse = () => {    this.setState({inputVal: {}}); }  render() {   return (     <form>       {[...Array(n)].map(         (item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} />       )}     </form>   ); } 

Demo below:

class MyApp extends React.Component {   constructor() {     super();     this.state = {       inputVal: {}     };   }      handleInputChange = (idx, {target}) => {     this.setState(({inputVal}) => {       inputVal[idx] = target.value;       return inputVal;     });   }      cancelCourse = () => {      this.setState({inputVal: {}});   }      render() {     return(       <form>         {[...Array(10)].map(  //create an array with a length of 10           (item, i) => <input value={this.state.inputVal[i] || ""} onChange={this.handleInputChange.bind(this, i)} />  //bind the index to the input handler         )}         <input type="submit" name="saveCourse" value="Create" />         <input type="button" name="cancelCourse" value="cancel" onClick={this.cancelCourse} />       </form>     );   } }  ReactDOM.render(<MyApp />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div>
like image 83
Chris Avatar answered Oct 04 '22 02:10

Chris