Evan Hickman
Evan Hickman

Reputation: 69

Preventing new line in textarea

I'm working on a chat feature (using Vue) and am using a textarea for my input so the overflow wraps and is more readable for users writing longer messages. Unfortunately, when the user keys down enter and submits, the cursor moves to a new line before submitting, making the UX feel off. Any ideas for how I could disable the newline on submit using vanilla Javascript? As you can see, I've tried adding a replace() function but to no avail.

My textarea:

<textarea id="btn-input" type="text" class="input-group_input" rows="4"
   placeholder="Type your message here..." v-model="body" 
   @keydown.enter="postReply()">
 </textarea>

My submit method:

postReply() {
  this.$http.post('/api/chat/' + this.session.id + '/replies', {
    body: this.body
    }).then((response) => {
      this.body.replace(/(\r\n|\n|\r)/gm,'');
      this.body = '';
      this.replies.unshift(response.data);
    }).catch((error) => {

    })
},

Upvotes: 3

Views: 6803

Answers (1)

Bert
Bert

Reputation: 82489

Use @keydown.enter.prevent="postReply". This will prevent the default action of the enter key, which is to created a newline, but still call your method.

Upvotes: 12

Related Questions