2

I want to take multiple input separated by comma from user using one input field. I used onChange function to store the user input in a state variable. It is storing each letter in each array index. For example, If I enter Red,Blue as input, it is storing like

Array[0]= R
Array[1]= e
Array[2]= d
Array[3]= ,
Array[4]= B
Array[5]= l
Array[6]= u
Array[7]= e

I want to store them like

 Array[0]= Red
 Array[1]= Blue

This is what my onChange handler look like:

changeHandler=(event)=> {
  this.setState({ 
    [event.target.name]:event.target.value
  })
}

How can I do that? I'm new to react js, any help would be appreciated. Thank you.

4
  • 1
    Post the onChange function code Commented Apr 17, 2018 at 13:49
  • changeHandler=(event)=>{ this.setState({ [event.target.name]:event.target.value }) } Commented Apr 17, 2018 at 14:01
  • Sounds like you're doing a .split('') instead of a .split(','). Commented Apr 17, 2018 at 14:05
  • i'm using .split(',') now, its working. thank you Commented Apr 18, 2018 at 5:16

1 Answer 1

1

Split your input values using comma delimiter:

this.setState({
    [e.target.name]:e.target.value.split(',')
  });

However, if you are using form its better to use onSubmit event to do these kind of operations. On 'onChange' just collect your input. Just a suggestion though.

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

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.