0

I'm making an app in which my inputs are controlled. I want a particular input to accept numbers only and I have achieved it, but it won't take numpad inputs for it takes them as letters (code range is 96 to 105)

This is the input:

<input onKeyDown = {(e) => this.handleChange(e)} type="text" value = {this.state.inputValue} />

And my function:

handleChange(e){

    let value = this.state.inputValue;

    if(e.keyCode >= 48 && e.keyCode <= 57 && value.length < 4)
    {
        this.setState(
            {
                inputValue: value + String.fromCharCode(e.keyCode)
            }
        );
    }
    else if(e.keyCode == 8)
    {
        this.setState(
            {
                inputValue: value.substring(0, value.length - 1)
            }
        );
    }
}
MarksASP
  • 494
  • 6
  • 15

1 Answers1

0

class Test extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      inputValue: null,
    }
  }
  handleChange(e) {
    let value = this.state.inputValue

    if (((e.keyCode >= 48 && e.keyCode <= 57) ||
        (e.keyCode >= 96 && e.keyCode <= 105)) &&
        value &&
        value.toString().length < 4
       ) {
      this.setState({
        inputValue: parseInt(value + String.fromCharCode(e.keyCode), 10)
      })
    }  if (e.keyCode >= 48 && e.keyCode <= 57 && !value) {
      this.setState({
        inputValue: parseInt(String.fromCharCode(e.keyCode), 10)
      })
    } else if (e.keyCode === 8) {
      if(value) {
        const stringSliced = value.toString().substring(0, value.toString().length - 1)
        this.setState({
        inputValue: stringSliced === "" 
              ? null
              : parseInt(stringSliced, 10)                                          
                                                        
        })  
      }
      
    }
  }
  render() {
    console.log("this.state", this.state)
    return (
      <input
        onKeyDown={
        e => this.handleChange(e)
        }
        type="text"
        value={
          this.state.inputValue
        }
      />
    )
  }
}

ReactDOM.render(<Test />, document.getElementById("root"));
<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="root">
</div>

This might help !!!

simbathesailor
  • 3,681
  • 2
  • 19
  • 30