What is the best way to have the v-model triggered by @onpaste in a textarea?

In my project, I have implemented a textarea that calls a specific function whenever the space key is pressed. This function is designed to check if the last part of the entered text resembles a URL. If it does, the function creates a preview below and removes that segment of text from the input field. Everything works smoothly in this scenario. Now, I am facing an issue where I want the same function to be triggered when a user pastes content into the textarea. The problem arises because the input is linked via v-model to post.description in the data object. Strangely, when @paste triggers the function, the data in post.description turns empty, whereas it remains populated when the function is called by pressing the space key.

<div id="post-share" class="form-group">
    <textarea
        id="post-description"
        class="form-control"
        name="post-description"
        cols="40"
        rows="5"
        @keyup.space="checkUrl"
        @paste="checkUrl"
        v-model="post.description"
    ></textarea>

The function implementation looks like this:

checkUrl() {
    if (this.post.video_link === "") {
        console.log("entro 1");
        let link = [];
        const regex = /((?:https?:|www\.)[^\s]+)/g;
        let url = this.post.description.match(regex);
        console.log(this.post.description);

        if (url) {
            console.log("entro 2");
            url.forEach((match, groupIndex) => {
                link = match.split("=");
                this.$set(this.post, "video_link", link[1]);
                this.is_there_url = true;
                this.post.description = this.post.description.replace(match, "");
            });
        }
    }
}

As mentioned earlier, the if (url) condition fails when triggered by @paste due to the empty this.post.description. Any ideas why it's only empty on @paste and not when the space key is pressed?

Answer №1

It's possible that the @paste event is firing before the value is bound to post.description.

Consider using a watcher instead.

<textarea 
     id="post-description" 
     class="form-control"
     name="post-description"
     cols="40"
     rows="5"
     v-model="post.description"
></textarea>

Then, in the script section, include:

computed:{
    postDescription(){
        return this.post.description
    }
},
watch: {
    postDescription() {
      this.checkUrl()
    }
}

I'm not certain of your exact goal with the model, but make sure to add conditions within the watcher to avoid executing the method on every new character input for better performance.

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

Using a forEach loop to generate a fresh HTML element

I am trying to dynamically create a new image element in JavaScript while iterating through my array using a forEach loop. Here is the code snippet that I have written for this task: axios.get('https://jsonplaceholder.typicode.com/photos', {param ...

Having trouble uploading a file in PDF format (*.pdf)

I'm attempting to use Node's readFile method to read a file and then send it as a response so that the user can download it. This is the code snippet I have: async function(req, res, next) { const query = { id: req.params.id }; // @ts-ignore co ...

Using Axios to fetch data from an API

Recently, I delved into learning about APIs and created an application utilizing the F1 Motorsport API from RapidAPI. The API response structure includes driver standings for the 2024 season. { "standings":{ "id":"0", "name":"Driver", ...

The jQuery mobile Multiselect feature is not correctly updating the selected attribute

In my jQuery mobile custom multiselect, when I choose an item, the list of items in the HTML select tag does not update with the selected attribute. Check out the Multiple selects example on the page: <div data-role="fieldcontain" class="ui-field- ...

Tips on harnessing the power of AngularJS $scope

In need of assistance! I have a paragraph and a counter that I want to update whenever the user clicks on the paragraph, all using AngularJS. Below is the code snippet I've come up with: <!DOCTYPE html> <html> <head> <script src= ...

Tips for assigning multiple Angular2 variables in Jquery on change

I am having trouble assigning more than one variable in jQuery within Angular2. Here is my current code: jQuery('.source-select').on('change',(e) => this.updateForm.value.sources = jQuery(e.target).val().split('--')[0]); ...

Explore an object to locate an element along with its parent

Here is an example of an object: $scope.categories = [ { value: 'One', id: 1, childs: [ { value: 'Two', id : 2, childs: [ { v ...

Grab the source attribute of the <img> tag (identified by class) across numerous HTML pages

Here is an example: A website has the URL , where xxxx represents an integer between 1 and 1935. On each page, there may be an <img class="thumbnail" src="Images\Robots\{robotname}.png">. However, not all pages have th ...

The best practices for integrating Firebase with REST APIs

While searching for a tutorial on integrating REST APIs with Firebase, I came across numerous code snippets utilizing the curl method calls or other helper libraries. However, what I couldn't find were the basics - such as where to call these methods ...

What is the best way to ensure the button remains fixed at the top when scrolling on a Window?

Can someone help me with fixing a button on top when scrolling the window? I am using JavaScript for this, but suggestions related to JavaScript or jQuery are welcome. See the image provided through this link for clarity on the issue. Here is my button co ...

Encase the entire section following cloning with JQuery

Make sure to check out the jsfiddle demo linked below before proceeding: JSFIDDLE I need to transform the original structure as shown below: <div class="out"> <a>im here</a> <a>to save</a> <a>our</a> ...

Can the Angular link function activate the change event?

I am facing an issue with my Angular directive that includes a link function. Inside this function, I am initializing a jQuery plugin which can be seen in action here: https://plnkr.co/edit/58nOhypt6FRdI4At5jwu. The problem arises when every time the dire ...

Fixed bar on top, revealed only when the scroll attempts to conceal it

I have placed a menu on the top section of my website, but not at the very top. I would like it to stick to the top of the page when the user scrolls down and disappears from view. However, if the title is still visible, I want the menu to remain below it ...

Creating TextInputs in a single row in React Native: A step-by-step guide

I'm having trouble creating 3 TextInputs in a single row. Despite setting flexDirection to 'row', the text inputs are not appearing on the device. var SampleApp = React.createClass({ render: function() { return ( <View style={styles.co ...

To ensure at least one checkbox is selected, retrieve the values from the checkboxes and proceed to store them in a state variable for validation

Our form allows users to submit multiple answers in a checkbox format. I'm utilizing the useState hook to manage the answers and validate the array size to determine if the button should be enabled or disabled. Currently, the issue is that even after ...

Creating a copy of Angular response data to ensure that modifications to one instance do not impact the other

I am facing a scenario where I have an angular controller that is connected to a node/express server. The response data for a request is obtained using $http.get and can be stored as response=$scope.x. This means that interacting with or changing x will al ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

Attempting to showcase data retrieved from various API calls

I am currently facing an issue where I am retrieving stock/share names from my MongoDB database and attempting to display their prices by making API calls for each of them in my component. However, I am only receiving the price for the last stock. Below i ...

During the rendering process, the property "instance" was attempted to be accessed but is not defined

I am having trouble creating a Contact Us page using v-model. My code keeps throwing these errors: Property "inputted_name" was accessed during render but is not defined on instance Property "inputted_email" was accessed during render but is not defined o ...

Sending personalized list attributes through JSON to JavaScript in ASP.NET

Below is a custom list I created for pagination of my results: public class PagedList<T> : List<T> { public int PageIndex { get; set; } public bool HasNextPage { get; set; } // ... } I aim to pass this list via JSON to the View: ...