Dan Dan - 2 months ago 7
React JSX Question

How to submit a form as soon as all inputs are filled in React?

I have a form like this(simplified):

handleSubmit(e){
e.preventDefault();
}
render(){
return (
<form onSubmit={this.handleSubmit.bind(this)}>
<input type="text" maxLength="1"/>
<input type="text" maxLength="1"/>
<input type="text" maxLength="1"/>
<input type="text" maxLength="1"/>
</form>
)
}


As you can see, there is no button to submit a form since I want to automatically submit a form when a user filled all inputs.

Also, just to be clear, I'm not trying to find out how to submit a form with enter key.

How can I achieve this?

Answer

For an input create value attribute state and assign an onchange handler to the input. On every change set the state of the input state variable. If the value of all four of the state variables is set then call the handleSubmit function. Below is the sampple snippet.

class App extends React.Component {

constructor() {
  super();
  this.state = {
    
  }
}
  handleSubmit(){
   console.log('Perform submit acction now');
}
  handleChange(e) {
   this.setState({[e.target.id]: e.target.value}, function() {
   var obj = this.state
   var count = 0;
   if(Object.keys(this.state).length == 4) {
   Object.keys(this.state).forEach(function(key){
     if(obj[key] !== '') {
       count++;
     }
   });
     if(count == 4) {
       this.handleSubmit();
     }
     }
});
  }
render(){
   return (
       <form ref="form1" onSubmit={this.handleSubmit.bind(this)}>
          <input type="text" id="inp1" maxLength="1" onChange={this.handleChange.bind(this)} value={this.state.inp1} />
          <input type="text" id="inp2" maxLength="1" onChange={this.handleChange.bind(this)} value={this.state.inp2}/>
          <input type="text" id="inp3" maxLength="1" onChange={this.handleChange.bind(this)} value={this.state.inp3}/>
          <input type="text" id="inp4" maxLength="1" onChange={this.handleChange.bind(this)} value={this.state.inp4}/>
       </form>
   )
}
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="app"></div>