S.M_Emamian
S.M_Emamian

Reputation: 17383

Focus next input once reaching maxlength value - reactjs

these are my inputs:

<input onChange={(event)=>this.setState({cardNumber4:event.target.value})}  name="card4" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" tabindex="4" maxlength="4" />
<input onChange={(event)=>this.setState({cardNumber3:event.target.value})}  name="card3" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" tabindex="3" maxlength="4" />
<input onChange={(event)=>this.setState({cardNumber2:event.target.value})}  name="card2" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" tabindex="2" maxlength="4" />
<input onChange={(event)=>this.setState({cardNumber1:event.target.value})} name="card1" type="text" class="form-control col-xs-3 col-sm-3" style={{paddingLeft:'0px !important;'}} required="" autocomplete="off" tabindex="1" maxlength="4" />

now I want to go next input after filled first input (I don't want use tab or next key). How can I do?

Upvotes: 0

Views: 1645

Answers (2)

mfakhrusy
mfakhrusy

Reputation: 1208

You can programmatically focus an input by using react refs and a data-property from your input. This is a rough example, change it according to your needs:

handleInputChange(e) {
  const index = e.currentTarget.dataset.index;

  if (e.target.value.length > 4) {
    this[`textInput${index + 1}`].current.focus()
  }

}

...
...
...

<input onChange={this.handleInputChange} data-index={1} ref={this.textInput1} name="card1" type="text" tabindex="4" maxlength="4" />
<input onChange={this.handleInputChange} data-index={2} ref={this.textInput2} name="card1" type="text" tabindex="4" maxlength="4" />


You can create ref by using React.createRef() on the constructor. Example:

this.textInput1 = React.createRef();
this.textInput2 = React.createRef();

Upvotes: 1

Dor Shinar
Dor Shinar

Reputation: 1512

In that case you should use refs. An example from the react docs:

class CustomTextInput extends React.Component { 
  constructor(props) { super(props); // create a ref to store the textInput DOM element
  this.textInput = React.createRef();
  this.focusTextInput = this.focusTextInput.bind(this); 
} 
focusTextInput() { 
  // Explicitly focus the text input using the raw DOM API 
  // Note: we're accessing "current" to get the DOM node 
  this.textInput.current.focus(); 
}
  render() { 
  // tell React that we want to associate the <input> ref 
  // with the `textInput` that we created in the constructor 
return ( <div> 
  <input type="text" ref={this.textInput} /> 
  <input type="button" value="Focus the text input" onClick={this.focusTextInput} /> 
 </div> ); 
} 
}

Upvotes: 0

Related Questions