When an element in vue.js is selected using focus, it does not trigger re

One of my tasks involves tracking the last selected input in order to append a specific string or variable to it later on.

created: function () {
    document.addEventListener('focusin', this.focusChanged);
}

focusChanged(event) {
    if (event.target.id !== 'variable-search') {
        this.lastElement = event.target;
    }
}

Everything seems to be functioning properly, as clicking on an input field updates this.lastElement with the focused element. All these input fields have a v-model, which can either be a string within an object or simply a standalone string.

The issue arises when I attempt to update the value using:

this.lastElement.value += variable;

Vue fails to detect these changes, and even in the Vue Developer tools, the string does not get updated. However, the input field itself displays the updated value. It appears to be some sort of reactivity problem.

Interestingly, adding a new character into the v-model field triggers the update. So, the problem only occurs when I update the string using this.lastElement.

Since the input fields are dynamic and their number is unknown, I am unsure how many fields there are or how many lists exist. Therefore, I need Vue to re-render the variable once the value of lastElement has been updated.

Edit

I attempted using @focus as shown in this example:

<input v-model="testVar" @focus="lastElement = testVar">

If I later update lastElement, it does not reflect those changes in testVar, but only in lastElement.

Answer №1

When modifying values in DOM elements programmatically, DOM events are not triggered. The v-model feature depends on the input event (or change event when using .lazy) to update the associated variable. By dispatching these events when updating the input value, the variable will be updated accordingly.

new Vue({
  el: '#app',
  data: {
    items: ['one','two','three']
  },
  methods: {
    addAddress() {
      this.lastElement.value += 'address';
      this.lastElement.dispatchEvent(new Event('input'));
      this.lastElement.dispatchEvent(new Event('change'));
    },
    focusChanged(event) {
      this.lastElement = event.target;
    }
  }
})
<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
<div id="app">
  <div v-for="item, index in items">
    <input v-model="items[index]" @focus="focusChanged">
    {{item}}
  </div>
  <button type="button" @click="addAddress">+address</button>
</div>

Answer №2

To easily update the values of input elements, you can assign a unique ref to each one. Here's an example of how an input element can be structured with a ref:

<input v-model="testVar" ref="input1" id="input1" @focus="focusChanged">

Within your methods section, add a function like this:

 methods: {
      focusChanged(event) {
            if (event.target.id !== 'variable-search') {
                this.lastElement = event.target.id;
            }
        },
 }

To update the value when needed, use:

this.$refs[this.lastElement].value += variable;

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

Determine the output by applying a constant value to the input

I'm having an issue with a loop function. The goal of the code is to allow users to enter a quantity of goods they want to buy, and then JavaScript calculates a fixed value based on the chosen quantity, which should be printed out. This functionality ...

Easily move a group of HTML elements at the same time with a simple

Exploring HTML5 Drag and Drop with Multiple Elements When it comes to dragging and dropping multiple elements in HTML5, there seems to be a limitation with the default draggable attribute. This attribute allows only one element to be dragged at a time, ma ...

Ways to define two ng-change functions simultaneously

I am currently working on implementing the phonechange and emailchange functions simultaneously. My goal is to trigger an alert message when both the phone number and email entered are valid. Any assistance from you all would be greatly appreciated! $sc ...

Determining when all textures have successfully loaded in Three.js and ensuring there are no lingering black rectangles

I'm currently developing a web platform that allows users to customize and preview 3D house models. If the user's browser doesn't support WebGL, the server renders the house and sends screenshots to the client. However, if the screenshots ar ...

Modal box fails to refresh content

Currently, I am in the process of learning how to modify my blog using a modal window. However, when I click on the edit button within the modal, an error message 'Failed to execute 'fetch' on 'Window': Invalid name' appears i ...

Ways to conceal a parameter in Angularjs while functioning within the ng-bind directive

I am using Angular to create the final URL by inputting offer information. Below is the code snippet: <!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> <body> ...

"Use jQuery to toggle the slide effect for the first element of a

Below is the HTML code snippet: <div class="row header collapse"> Content 1 <i class="fas fa-chevron-circle-up" ></i> </div> <div class="instructions-container"> <div></di ...

The DOM fails to reflect changes in the data variable in VueJS

I am facing an issue while trying to update an array of arrays and display it as a reactive variable, however the DOM does not seem to reflect those changes. To achieve this, I have two components - a parent component and a child component: Parent Compon ...

Looking to conduct date comparisons within angular-ui-grid?

I'm currently working on an application that utilizes angular-ui-grid to display form data. One issue I'm facing is how to compare the submission date obtained from an API call with the current date within ui-grid, in order to calculate the numbe ...

What is the best way to continuously click a JavaScript link until it disappears?

Many websites utilize single-page pagination to display more content with each click. It can be beneficial to view all the content on one page, such as for web crawling purposes. Much like automatically clicking a button using Greasemonkey, how can JavaScr ...

Transform URL in AngularJS Service

An issue I'm facing with the app I'm developing is that users need to be able to change the IP address of the server where the REST API is hosted. The challenge lies in the fact that while the address is stored in a variable that can be changed, ...

Material UI filterSelectedOptions not functioning properly on initial search with multiple autocomplete

When I utilize the filterSelectedOptions prop in my autocomplete feature, it functions as intended when using a pre-defined chip. Check out image1 for an example: image1 However, when a brand new typed option is entered, it ends up duplicating multiple ti ...

How can I utilize JavaScript to generate a dynamic value in a URL and then submit it through a form?

One of my clients has requested the ability to send out unique URLs to their customers in order to track which links are being utilized. Despite my suggestion to use Google Analytics for this purpose, they have specifically asked to avoid it. Their reques ...

Guide on generating a dynamic loop in JavaScript using the group name as a variable

I have been attempting to organize a group, dynamically ungroup it, and then create a loop with each element of the group. Despite reviewing multiple examples, I have not been able to solve the following issue: The grouping is done based on the "tipo" pro ...

I'm interested in knowing if it's feasible to develop unique jQuery selectors that can navigate ancestors, such as a :closest or :parents selector

As a developer who frequently creates jQuery plugins, I often find myself using custom jQuery selectors like :focusable and :closeto to simplify common filters in my code. For example, the :focusable selector is defined as follows: jQuery.extend(jQuery.e ...

Display a loader in Vue JS at the start and then remove it once the response is received

To achieve the functionality of showing a loader initially and hiding it after receiving a response, you can use the following code: <template> <div id="app"> <Document :loading="loading"> </div> </tem ...

Guide on how to verify user identities with Azure AD in a Vue.js interface and backend developed with .Net 5

Our team is currently in the process of transitioning from .Net MVC to a Vue.js front-end. We had originally implemented a custom Attribute in our MVC version that utilized Azure AD for user authentication on specific pages. This attribute verified if user ...

Capturing the input value from a text box within a table cell, saving it in an array using Javascript, and then transmitting it back

I have a PHP-generated table displayed on my website. The table consists of two rows - the first row contains headers, and the second row contains text boxes inside each cell. My goal is to allow users to input values into these text boxes, then retrieve t ...

Does Quasar q-select create an additional dropdown menu?

Here is how I am currently using Quasar's q-select: <q-select ref="search_shares" dense use-input v-model="search_model" :options="quick_search" @filter="quick_search_search" @input="open_sharelink" v-if="Quasar.Screen.gt.md == true"> <t ...

What is the best way to delete an item from a list using VUE?

I am working with a container that contains various div elements. I am trying to remove specific ones when clicked. However, the code I have taken from a Vue page example is not functioning as expected and I can't seem to figure out why. Any suggestio ...