1

I need to have an input box to be only restricted to numeric values when the type is text. I took a look at this answer, but it does not seem to work. HTML text input allows only numeric input

<input type="text" onKeyPress={(event) => {
    if (event.charCode >= 48 && event.charCode <= 57 || event.charCode >= 96 && event.charCode <= 105) {
        return true;
    } else {
        return false;
    }
  }}
  className="form-control"
  maxLength="5"
  ref="zip"
  placeholder="Enter Zip Code" />
henhen
  • 1,038
  • 3
  • 18
  • 36
  • Care to change the condition like this: if ((event.charCode >= 48 && event.charCode <= 57) || (event.charCode >= 96 && event.charCode <= 105)) { return true; } Look at that extra parentheses – kidz Jan 08 '18 at 23:54

3 Answers3

2

Since you're using React, you can make <input> a controlled component and decide when you want to change the state:

class ZipCodeInput extends React.Component {
  state = {
    value: ""
  }

  render() {
    return (
      <input
        type="text"
        onChange={(event) => {
          if (isNaN(Number(event.target.value))) {
            return;
          } else {
            this.setState({ value: event.target.value });
          }
        }}
        maxLength="5"
        placeholder="Enter Zip Code"
        value={this.state.value}
      />
    );
  }
}

I modified the condition in an attempt to make the intention more obvious.

silvenon
  • 2,068
  • 15
  • 29
1

You can use number type of input tag in HTML. HTML supports the standard number input type. The formula is like this.

input type="number" placeholder="Enter Zip Code"

1

I've put together an alternative way of accomplishing this at https://codepen.io/anon/pen/gooyEy.

The code is as follows:

<input
  type="text"
  autofocus
  onkeypress="return onlyNumbers(event)"/>
const onlyNumbers = (event) => {
  return !isNaN(event.key);
}

You can also use this if you're looking for a one-liner:

<input
  type="text"
  onkeypress="return !isNaN(event.key)"/>
fl0psy
  • 481
  • 1
  • 4
  • 5