Tips for eliminating the space between strings after pasting them into vue2

Dealing with two input fields that require removing spaces between strings has proven to be a challenge. I initially attempted to use event.clipboardData.setData, but unfortunately, it did not yield the desired outcome. Afterward, I resorted to using this.Name_of_my_state. However, this approach resulted in both the pasted item and the space-removed item being displayed. Let's delve into my code for further clarity.

<template>
  <span>
    <input class="form-control inputHeight"
        @keydown.space.prevent
        @paste.space="remove_on_paste"
        v-model="floatingData.from_id">
    <input class="form-control inputHeight"
        @keydown.space.prevent
        @paste.space="remove_on_paste"
        v-model="floatingData.to_id">
  </span>
</template>

Initially, this method was unsuccessful:

new Vue({
  data() {
    return {
      floatingData: {
        from_id: "",
        to_id: ""
      }
    }
  },
  
  methods: {
    // Remove space on paste
    remove_on_paste(event) {
        let main_text = event.clipboardData.getData("text");
        event.clipboardData.setData("text", main_text.replace(/\D/g, ""));
    }
  }
})

Result:

https://i.sstatic.net/aYnxn.png

Subsequently, I attempted a different approach which resulted in both the copied and replaced values being pasted:

new Vue({
  data() {
    return {
      floatingData: {
        from_id: "",
        to_id: ""
      }
    }
  },
  
  methods: {
    // Remove space on paste
    remove_on_paste(event) {
        let main_text = event.clipboardData.getData("text");
        this.floatingData.from_id = main_text.replace(/\D/g, "");
    }
  }
})

Result:

https://i.sstatic.net/I9UA4.png

Answer №1

I successfully implemented the desired functionality where trailing whitespace is automatically removed when pasting a string. This was achieved by using event.preventDefault() to prevent default browser behavior after paste, and utilizing main_text.trim() to eliminate whitespace. Please confirm if this meets your requirements.

(Tested on Google Chrome 91, with reference to this codesandbox)

<template>
  <span>
    <input class="form-control inputHeight"
        @keydown.space.prevent
        @paste.space="remove_on_paste"
        v-model="floatingData.from_id">
    <input class="form-control inputHeight"
        @keydown.space.prevent
        @paste.space="remove_on_paste"
        v-model="floatingData.to_id">
  </span>
</template>

<script>
export default {
  data() {
    return {
      floatingData: {
        from_id: "",
        to_id: ""
      }
    }
  },
  
  methods: {
    // Remove space on paste
    remove_on_paste(event) {
      let main_text = event.clipboardData.getData("text");

      event.preventDefault();
      this.floatingData.from_id = main_text.trim();
    }
  }
};
</script>

Answer №2

To address this issue, it is recommended to utilize watchers:

data()
{
  return {
    user_name: '',
    email_address: '',
  }
},
watch:
{
  user_name()
  {
    this.$nextTick(() =>
    {
      this.user_name = this.user_name.replace(/\s+/g, '');
    })
  },
  email_address()
  {
    this.$nextTick(() =>
    {
      this.email_address = this.email_address.replace(/\s+/g, '');
    })
  },
}

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

"Proceeding to" express this redirection

Greetings, I am currently struggling to understand why res.redirect('/index') is rendering like this: <p>OK. Redirecting to <a href="/index">/</a></p> Instead of directly redirecting on the page. I searched through th ...

What could be the reason for the onClick event functioning only once in HTML?

Below is the code snippet containing both HTML and JavaScript. However, the issue I am facing is that the onclick event only seems to work for the first <li>. <!DOCTYPE html> <html> <body> <ul class="list"> <li ...

Utilizing optional parameters with React Router

Imagine I have a page at http://www.example.com/page/#/search set up with the following routing: <Router history={hashHistory}> <Route path='/search/' component={SearchPage} /> </Router> When a user performs a search using t ...

Enhance your web forms with jQuery Chosen's automatic formatting feature

Having trouble adding a feature to my multi-select input box using jQuery Chosen. The current functionality allows users to enter custom values not in the list. The new feature should automatically format numbers entered by users, for example: User input ...

Finding and comparing a specific portion of a text in JavaScript: A guide

Can you help me with a JavaScript algorithm that can find a substring within a string? subStringFinder('abbcdabbbbbck', 'ab') This should return index 0. Similarly, subStringFinder('abbcdabbbbbck', 'bck') should ...

Discover optimized ways to search for and sort through deeply embedded objects

In Vue3, I am working with the object $products, which looks like this: [{ "id": 1, "item": "Product 1", "productcategories": [{ "id": 300, "title": "Category300&quo ...

Create a standard chart with a colored map using Three.js

Recently, I dove into the world of Three.js and found myself on a mission to convert a color map into a normal map. My goal is to create a normal map similar to [image 2], based on the color map shown in [image 1]. Instead of simply uploading files, I wa ...

Tips on adding custom fonts for text geometry in three.js

Currently, I am delving into the realm of three.js to create text geometry, although my expertise in JavaScript is fairly limited. Initially, I attempted to utilize my custom JSON font, which resulted in the same error encountered when using fonts from th ...

select attribute not saving on change

My select input has the multiple attribute being set using jQuery. Interestingly, after confirming through console.log that the code functions correctly, the multiple attribute seems to disappear when I check again. Any ideas on why this is happening? The ...

Guide to generating an array entry for every line of a text file in node.js

Struggling with converting each line of a text file into an array entry in node.js The array I am working with is named "temp." The code below successfully prints out each line: var temp = []; const readline = require('readline'); const fs = re ...

Angular: Deciding Between Utilizing Boolean @Input and Attribute @Directive - What's the Best Approach?

My goal with Angular is to create a "directive" that can add functionality to my component, specifically adding a myPortlet with a close button when using the directive myHasCloseButton. <myPortlet myHasCloseButton>...</myPortlet> In explori ...

Exploring the functionality of Next.js with Links and routes

Currently, I am facing an issue with the popover menu in my header that displays products. The problem arises when I click on a product in the list; it navigates correctly to the path "products/some-product" regardless of the selected item. However, if I a ...

Having trouble installing Bootstrap using the `npm i bootstrap` command? It seems like the

The npm i bootstrap command is not working when trying to install Bootstrap. Nothing is being added to the packages.json file or node_modules directory. Here are the dependencies listed in the package.json file: "dependencies": { "@angu ...

Struggling to efficiently handle imported JSON data using VUE.JS JavaScript?

Struggling to extract specific information from JSON data that I need to import. Here is the sample data I'm working with: I am trying to extract details like the name, description, and professor for each entry. This is how I'm importing the d ...

Text aligned at the center of the Y and X axis

I am looking to center my content along the Y axis instead of only on the X axis. To prevent the page from expanding beyond its current size, I have applied the following CSS: html { overflow-y: hidden; overflow-x: hidden } What I want to achieve is havi ...

Storing and retrieving an HTML editable array using COOKIES in JavaScript

In my code, I have created an editable array where you can input student information. A button computes the grade for each student at the end of the line. Additionally, there are buttons to add rows for students and columns for different assignments. Now, ...

Would you like to learn how to extract data from a specific textbox using jQuery and save it to a variable when the textbox is in

Below is a textbox that I am working on: <input type="text" name="company" id="company" required /> I am trying to figure out how to use jQuery to capture the values inside the textbox whenever they are typed or selected. Despite my efforts, I hav ...

Is there a way to trigger Material-UI SpeedDialAction onClick events only when the SpeedDial is open and clicked, not when it is hovered over?

After making a modification to material-ui's <SpeedDial> component by removing the onMouseEnter={handleOpen} prop, I noticed that the onClick event within the <SpeedDialAction> component no longer triggers when clicking on a menu item. It ...

Managing input debounce durations in VueJS with dynamic wait times

Managing debounce functionality for input fields in Vue is usually straightforward. However, I am facing a challenge when it comes to making the debounce wait time configurable on a per-field basis. Each of my input fields is associated with an object str ...

I'm experiencing difficulties with updating my model while utilizing the ngResource module

Encountering a minor issue with Angular at the moment. Employing the $ngResource module to fetch "comments" from my server: var app = angular.module('app', ['ngResource']); app.factory('comment', function($resource) { r ...