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

AJAX cached outcomes

Trying to educate myself on AJAX using w3schools.com, but struggling with a particular example: xhttp.open("GET", "demo_get.asp", true); xhttp.send(); In the above example, there might be a cached result. To prevent this, you can include a unique ID in t ...

The OnChange event seems to be malfunctioning as it is not being triggered despite other parts of the code functioning properly

Check out the code snippet below: import React, { useState } from "react"; function IP() { const [ipAddress, setIPAddress] = useState(""); const handleInputChange = (event) => { const inputValue = event.target.value; // ...

To add additional nested data to a JSON object in JavaScript, you can use the push method or update

Looking to enhance the nested object data within my existing object The current structure of the JSON object array resembles this: var orderDetails = [{ "utilityType": "Electric", "firstName": "ROBERT", "lastName": "GUERRERO", "utilityList": [{ ...

What is the best way to conceal an HTML element on a particular page that is already styled as (visibility: visible), but only if its child has a specific class assigned to it?

I have a grid of content and posts displayed on multiple webpages. Users can select specific items from the grid to navigate to more detailed information on another page. Each webpage has its own grid which I want to filter based on a specific class. The ...

onmouseleave event stops triggering after blur event

I am facing an issue with a mouseleave event. Initially, when the page loads, the mouseleave event functions correctly. However, after clicking on the searchBar (click event), and then clicking outside of it (blur event), the mouseleave functionality stops ...

Tips for increasing the height of a popover when clicked

When a user focuses on the password input, a popover displays information. At the bottom of the popover, there is a link. How can I make the popover expand when the user clicks on this link? I have tried adding an !important class for the height value, us ...

"eliminate" ng-if after the condition becomes true

I'm curious to know if it's possible to deactivate or remove ng-if once its value becomes true? In my project, I've constructed a tree structure using a recursive directive. Each branch in the tree has a <div ng-if="visible"> element ...

Access files directly through our convenient file storage site

I'm currently delving into the world of angular JS, and I've come across $https. I was looking to upload a file called db.php which includes: { "vcRecords": [ {"name":"Madison" ,"nickName":"Madilove" ,"coderType":"Injection / Fortre ...

The submit button is unable to initiate the ajax function

I encountered an issue with my code while attempting to separate my form function into a different PHP file and utilize an Ajax function to call the form based on the IDs. However, after separating the form function, the submit button no longer triggers th ...

Next.js API Endpoint Call Resulting in Empty Object Returned by Fetch Function

Having an issue with making an API call in Next.js to delete an item from the database. I'm using the "body" field of the fetch to send a string to the API. The fetch call is within a Next.JS page, and the API endpoint is located in the API folder gen ...

Is the AngularJS Date property model sending an incorrect value to the server?

There are some puzzling things I am trying to figure out. When using datetimepicker, the Date and time selected appear correctly on the screenshot. The value in the textbox is accurate The model's value in console is correct (but hold on a second... ...

Converting a TypeScript object into a JSON string

When working with TypeScript, I am facing a challenge while trying to initialize an object that requires a JSON string for the "options" parameter. Specifically, it pertains to the object mentioned here. It is crucial that the options parameter be in JSON ...

I keep running into errors whenever I try to run npm install in my React JS project. The only way for me to successfully install dependencies is by using npm install --force. How can I go about resolving these

I am encountering this error message while working on my project: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @mui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681b1c11040d1b ...

How can you use JavaScript to assign a data value to a hyperlink?

I'm currently facing an issue with assigning a value to the data-attribute of an anchor tag. Below is the code snippet in question: <script> window.onload = function(){ document.getElementById("setcolor").click(); } var color = "red"; document ...

What are some effective methods for incorporating large JSON data into a node.js script?

What is the best way to import a large JSON file (550MB) into a node.js script? I attempted: var json = require('./huge-data-set.json') The script was run with an increased --max-old-space-size parameter node --max-old-space-size=4096 diff.js ...

Traverse a deeply nested JSON structure

I need assistance with looping through a complex JSON object using only JavaScript. My goal is to log each item along with its properties into the console. const nested_json = { "item1":{ "name": "banana", ...

combine object with an array attribute

If we have the following objects: let firstObject = {items: ["apple"]}; let secondObject = {items: ["orange"]}; and then execute Object.assign(firstObject, secondObject); the new state will be: firstObject.items[0] //"orange" firstObject.items === sec ...

Instructions on including a directory in the package.json file for publication on npm

I am facing an issue when attempting to publish a module in the npm repository as it is not recognizing the 'lib' folder. Even though I have included it in the package.json file as shown below, the 'lib' folder contents are not being re ...

Transferring an MSAL token to the backend with the help of Axios

I encountered an issue while attempting to send the user ID, which was previously decoded from a JWT token along with user input data. The problem arises when I try to send the data and receive an exception in the backend indicating that the request array ...

Developing a Multi-Faceted Array Utilizing SQL Data

The requirement of the plugin I am using is to provide it with an array structure in JavaScript that looks like this: var data = [ { "id": 1, "name": "University1", "list": [ {"id": 1, "name": "Dorms", "list": ...