0

I have a form with a textarea where users can put comments, and then trigger a onClick (when the form is submitet via the button).However, I cant get the value of the input, for example if a user writes "test", I want it to get into the handleSubmit function.

My form

<form onSubmit={this.handleSubmit.bind(this)} method="POST">
    <label>Skicka</label>
    <textarea placeholder="Type in comments (allergis etc.)" name ="name" ref ="name"></textarea>

    <button className="btn" type="submit">
        Send
    </button>
</form>

//my handler

public handleSubmit = event => {
    event.preventDefault();
    console.log(event.name.value)
}

3 Answers 3

1

You have to save the textarea value separately in the onChange method of the textarea like this (for class component):

<form onSubmit={this.handleSubmit.bind(this)}
   method="POST"

   >
    <label>Skicka</label>
    <textarea
         onChange={this.setComments}
         placeholder="Type in comments (allergis etc.)"
         name="name"
         value={this.state.comment}/>

<button className="btn" type="submit">
    Send
</button>
</form>   
// The save function
const setComments = e => this.setState({comment: e.target.value});

This will save the textarea input in your local state and you can access it in your submit function with this.state.comment.

Hope this helps. Happy coding.

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

2 Comments

you can also directly call the setState() on text area on change event, like onChange ={e=> this.setState({comment: e.target.value})
But for class components, that's bad practice, because it creates a new function on every render.
1

As you are using Uncontrolled Component. You can make use of ref to get value.

handleSubmit = (event) => {
  event.preventDefault();
  console.log(this.refs.name.value)
}

Demo

Note: In React you should never add method="POST" and action attribute's on form.

Don't add public keyword to your function (if you are not using typescript).

Better approach to work with form values, is Controlled Component

Comments

1

You can fix it by changing the handleSubmit method. Check below updated method.

public handleSubmit = event => {
   event.preventDefault();
   console.log(event.target.name.value)
}

But if you are work with React application then update the state variable via onChange event.

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.