Preventing the insertion of a line break when using Shift + Enter in Vuejs

Whenever I use a textarea to enter text, I find that I have to press Shift + Enter every time
to send the text. However, upon sending, it adds /n at the end. I prefer using the Enter key for newline instead of submitting the form.

Example: hello => hello\n

If the image is not selected, it can be sent by pressing the Enter key: https://i.stack.imgur.com/wvRyL.png Here is my code:

    checkSubmitKey() {
      if (!this.isEnterSubmit) {
        this.sendMessage();
      }
    },
    
    
    onChangeInput() {
      this.getTextareaRef().addEventListener("keyup", (e) => {
        this.handlesaveDraftMessages()
        if (e.key === "Enter" && !e.shiftKey && this.isEnterSubmit) {
          this.sendMessage();
          this.resizeTextarea();
        }
      });
      this.resizeTextarea();
    },
    
    
    resizeTextarea() {
      const el = this.getTextareaRef();

      if (!el) {
        return;
      }

      el.style.height = "auto";
      let newHeight = el.scrollHeight;
      el.style.height = `${newHeight}px`;
    },
<textarea
     rows="1"
     id="roomTextarea"
     ref="roomTextarea"
     v-model="messageInput"
     :placeholder="$t('containers.admin.chat.chatPlaceholder')"
     class="room-footer-reply-textarea"
     @keyup="onChangeInput"
     @keyup.enter.shift.exact.prevent="checkSubmitKey"
     @click.self="checkmarkSeen"
     @paste="onPasteClipboard"
 />

How can I resolve the issue mentioned above?
Thank you for your assistance!

Answer №1

To avoid using keyup, try utilizing the keydown event and include preventDefault() when the Enter key is pressed without the shift key being held down:

document.querySelector('textarea').addEventListener('keydown', e => {
  if(e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault();
    console.log('send:', e.target.value);
  }
});
<textarea></textarea>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it more important to focus on passing props or making API requests the top priority in your web application structure

Context Currently, I am working on a Vue App utilizing the Composition API. My backend serves as the source of data for loading pages and components. Inquiry When it comes to structuring my app's architecture, should I prioritize passing props thro ...

JavaScript is experiencing an error where it cannot define a function, rendering it unable to generate a JSON object due to its inability to recognize that the

I've created a JavaScript script function that holds cart items for ordering food. This function takes two parameters: ID and price. Here is a snippet of my script file: <script> function addtocart(mitem, mprice) { var price = ...

Can you provide guidance on decompressing SVGZ files using JavaScript?

I'm currently working on implementing a high-resolution world map using SVGZ instead of the standard SVG format, aiming to provide my users with a more intricate and detailed visualization. Although I have experimented with utilizing js-deflate to de ...

Rows in a table will not decrease when added anew

On a page that allows adding and deleting rows from a table of input fields, the following code functions properly for existing fields. However, when attempting to add new rows and delete them in a sequential manner that requires replacing the ID and name ...

What makes it impossible to use var instead of let in ngFor?

My understanding is that in JavaScript, we typically use var and let for variable declarations. The main difference between the two is that var is scoped to the current function, while let is scoped to the current block. Therefore, theoretically I should b ...

The autosearch feature seems to be malfunctioning

I am currently working on implementing an autocomplete suggestion feature using the AutoComplete plugin from GitHub. I am using a combination of HTML, JavaScript, and CSS for this project. The functionality works perfectly when I hardcode the data in the f ...

Guide on embedding PHP/MYSQL array into an independent JavaScript document

I'm looking for guidance on how to insert an array from a PHP MySQL page into a separate JavaScript file. Can someone please help me with indicating where to include the PHP URL and provide the correct format for the PHP array code in order to achieve ...

GM Unable to Establish Cross-Domain Ajax Connection

Attempting to populate a form on a client's website with data from our database using a Greasemonkey script, but struggling with the same origin policy. I have tried using GM_xmlhttpRequest and even specified @grant GM_xmlhttpRequest but without succ ...

What could be the reason behind receiving an "undefined" message when attempting to access db.collection in the provided code snippet?

var express = require('express'); var GoogleUrl = require('google-url'); var favicon = require('serve-favicon'); var mongo = require('mongodb').MongoClient; var app = express(); var db; var googleUrl = new GoogleUrl( ...

Is it possible to retrieve the chosen options text from a select menu using jQuery with the feature of "Dynamic option values"?

I need assistance with displaying dynamic drop-down values where only the id values are presently available. What would be the best approach to achieve this? <div class="form-group"> <select class="wp-form-control" id="joblocation" name="jobl ...

Navigating through a large set of data in a web application can be challenging, but with the async await function

I have been working on an app that utilizes the GitHub API to display a user's repositories from Github. However, I am facing a challenge in fetching data from all pages as I can currently only retrieve repositories from one page. I attempted to addre ...

What is causing the Unhandled Rejection (TypeError) error after I move the object in my Redux application and receive the message "Cannot read property 'filter' of undefined"?

I've been working on a Redux application. I've made modifications to a couple of files, and here are the changes in the two files: index.js: const store = createStore( reducer, { propReducer: { day: 1, data: [], filte ...

NodeJS and DiscordJS: The art of modifying JSON files

Currently, I am grappling with the concept of appending data to a JSON file. The specific file in question (users.json) has the following structure: { "users": { "id": "0123456789", "name": "GeirAnders ...

Tips for iterating through a collection of arrays with jQuery

I am facing an issue with looping through an array of arrays and updating values or adding new keys to each array. Here is my current setup: var values = []; values['123'] = []; values['456'] = []; values['123&apo ...

Hiding the style tag in the head section of a Laravel-Vue.js application with Vue.js

Currently, I am working on a Laravel-Vue.js application. I have noticed that when Vue.js renders CSS, it appends some style tags in the HTML head as shown in the image below. Is there a way to hide these tags? My initial thought is that it can be achieved ...

Combining Versioning with BundleConfig.cs: A Comprehensive Guide

Encountering a recurring issue where changes made to CSS or Javascript files do not reflect in client browsers unless they manually refresh the page with ctrl+F5. This poses a challenge, especially in a school system with numerous users who may not be awar ...

Insects featuring a button and tooltip duo creating a captivating "pull-effect"

Why is the button pulling when I move the cursor over a camera? Is there a way to solve this issue? <div class="input-group-btn advanced-group"> <button class="btn btn-default" data-toggle="tooltip" data-placement="bottom" title="Send Imag ...

In JavaScript, you can update the class named "active" to become the active attribute for a link

My current menu uses superfish, but it lacks an active class to highlight the current page tab. To rectify this, I implemented the following JavaScript code. <script type="text/javascript"> var path = window.location.pathname.split('/'); p ...

Unexpected updates occurring in custom Google Sheet functions

Currently, I am utilizing a personalized function to retrieve price data for EVE Online. However, I am encountering an issue where the function is updating every 10-20 minutes, leading to a depletion of my daily URL Fetches quota. The primary function can ...

Utilize a class method within the .map function in ReactJS

In my ReactJS file below: import React, { Component } from "react"; import Topic from "./Topic"; import $ from "jquery"; import { library } from '@fortawesome/fontawesome-svg-core' import { FontAwesomeIcon } from '@fortawesome/react-fontaw ...