Gaurav Kumar
Gaurav Kumar

Reputation: 1231

How to put comma separator in input field in reactjs?

i have a form where i show previous field value in input tag. But, as i put type=number. then my .toLocaleString("en-IN") would'nt work.Also, i want to show comma in INR currency styles. i.e 12,25,789

Following is my code:

<Col lg="2">
    <Form.Control
        size="sm"
        // type="number"
        value={temp.originalAmount.toLocaleString("en-IN")}
        onChange={this.handlechangevalue.bind(
            this,
            item,
            keys,
            index
        )}
     />                  
</Col>

P.S been using react-bootstrap

Upvotes: 1

Views: 4448

Answers (2)

knightburton
knightburton

Reputation: 1164

It's not clear for me where you want to use the comma separated values but you can change between styles with the help of regexp and replace. Something like this:

// 1234567 => 12,34,567
const encode = string => string.match(/(\d{2})(\d{2})(\d{3})/).slice(1).join(',');

// 12,34,567 => 1234567
const decode = string => string.replace(/,/g, '');

(If your input is looks like two digits / comma / two digits / comma / three digits but this can be changed easly ofc.) Then you can convert the result to number before save into the state and the back to the comma version to display the user.

Also, I would use a text type on the input field an a regexp based validator. I'm using similar in case of dates.

Upvotes: 3

jsdeveloper
jsdeveloper

Reputation: 4045

I've come across this before. What you can do is restrict the type of input in your handlechangevalue function to numbers only. If any other character appears then discard/ignore it.

Something like this:

handlechangevalue(e) {
  if( parseInt(e.target.value) !== NaN ) {
    this.setState({val: e.target.value});
  }
}

Upvotes: -1

Related Questions