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" />
1
  • 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 Commented Jan 8, 2018 at 23:54

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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 Comment

I am not using number type since it adds the incremental arrows on the input box
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)"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.