The issue with VueJS's uppercase custom directive not functioning as expected

Here is a directive I created to convert an input's v-model to uppercase:

app.directive('uppercase', (el) => {
  el.value = el.value.toUpperCase()
})

However, after applying this directive, the resulting v-model displays the input value with the last character in lowercase.

  <template>
    <div>
      <input type="text" v-uppercase v-model="testInput" />
      <div>
        {{ testInput }}
      </div>
    </div>
  </template>
    
  <script setup>
    import { ref } from 'vue'
    const testInput = ref('')
  </script>

I'm confused as to why this behavior is occurring. Can anyone help me understand?

Answer №1

This scenario does not align well with using a directive since the model value should be the ultimate truth, not the input value.

Even if there are ways to work around updating the input value, as mentioned in another response, the issue persists because the directive does not impact the initial model value when the input remains unchanged.

A more direct approach would be to handle it at the model level:

const testInput = ref('');

watchEffect(
  () => { testInput.value = testInput.value.toUpperCase(); },
  { flush: 'sync' },
);

The use of v-model modifiers is designed for such modified behaviors. The documentation demonstrates how custom components can implement a modifier like uppercase transformation, as explained here.

Answer №2

Faced with a similar issue, I wasn't certain if this was the ideal solution, but I decided to implement the input event for proper functionality:

app.directive('uppercase', element => {
  element.value = element.value.toUpperCase();
  element.addEventListener('input', ($event: Event) => {
    if ($event.isTrusted) {
      element.value = element.value.toUpperCase();
      element.dispatchEvent(new Event('input'));
    }
  });
});

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

Issue with Vuex functionality not functioning within a child component

I've been struggling with this simple code that is causing me a lot of frustration. Both some-component and the root instance are logging errors to the console instead of binding from the vuex object. What could I possibly be overlooking here? var ...

Utilize modules within the AppModule to promote modularization and maintain separation of concerns in Angular 2

When using templates like those from the ASP.NET Core JavaScript services, typically a single module named AppModule is included. However, in my application, which is divided into two logical areas (AreaA and AreaB), I thought it would be better to use two ...

Positioning numbers on jQuery flot bar charts

I've implemented the jquery.flot.barnumbers.js plugin with the intention of displaying numbers on the bars using the Javascript plotting (charts) library for jQuery. This is a snippet of my code: $.plot("#placeholderByDay", [ { ...

I am looking to modify various attributes linked to Rails

My Desire for Reality I am looking to update multiple related values in Rails by sending an update request from JavaScript. While creating data was seamless, I encountered difficulties when attempting to update it. #Code JavaScript* export const actions ...

Encountered a problem when attempting to upload files to AWS S3 using React and React AWS S3

One issue I'm facing is receiving a strange response when trying to perform a put operation in my bucket. I am utilizing the react-aws-s3 package which only requires the bucket name, user keys, and region in its configuration. It's puzzling as t ...

AWS Cognito - ECS Task Fails to Start

I'm facing an issue with using JavaScript to execute a task in ECS Fargate. AWS suggested utilizing Cognito Identity Credentials for this task. However, when I provide the IdentityPoolId as shown below: const aws = require("aws-sdk"); aws.co ...

When I attempt to incorporate multiple sliders on a single page, I encounter difficulties in determining the accurate stopping position if the number of slides varies

I am having trouble setting the correct stop position for sliders with different numbers of slides on a page. When I have the same number of slides in each slider, everything works fine. However, I need to have a different number of slides in each slider ...

Utilizing a dropdown list in HTML to dynamically change images

On my HTML page, I have implemented a dropdown list box. My objective is to change an image and update a label based on the selection made from the dropdown list box. I already have an array called 'temp' which represents the number of items. The ...

Tips for repairing texture distortion on rounded corner surfaces in the three.js library

I managed to create a unique rounded corner plane by combining circle and plane geometries in my project. While the flat color in the rendered version looks great, I noticed that the textured part seems to get distorted and chopped up. If you want to tak ...

Removing data from the controller with JQUERY AJAX in a Spring MVC application

Could someone assist me with this issue? I am trying to implement ajax and sweetalert.js using the following repository: So far, everything is working well when I use onclick = "" to call my function. However, I need guidance on how to properly utilize th ...

Drawer in Material-UI has whitespace remaining at the corners due to its rounded edges

While using the Material UI drawer, I attempted to round the corners using CSS: style={{ borderRadius: "25px", backgroundColor: "red", overflow: "hidden", padding: "300px" }} Although it somewhat works, the corners appear white instea ...

using regular expressions to find unclosed font tags that match on a single line

Even though regex is not typically recommended for parsing HTML, in this case we are dealing with a single line string input to a function. For example: <font color = "#ff0000"> hello </font>. I want the regex pattern to match only if the tag ...

Obtaining the mouse position in JavaScript in relation to the website, preferably without relying on jQuery

I came across this code snippet on Ajaxian, but I am having trouble using cursor.y (or cursor.x) as a variable. When I call the function with it that way, it doesn't seem to work. Could there be a syntax issue or something else causing the problem? f ...

Deleting an item from a JSON object using Angular

Whenever I click on an item in the list, it generates an input text and adds the attributes of that input to a JSON. Currently, each time I click on an item multiple times, the JSON accumulates all the clicks. For instance, if I click 3 times on the first ...

What is the best way to utilize a single AngularJS 1.5 component multiple times within a single view?

While working on a project using AngularJS 1.5's new components, I encountered an issue with widget isolation. It seems that when I use the same widget multiple times, they end up sharing their controller or scope. I was under the impression that comp ...

Strange sudden increase in zoom between 1904 pixels and 1903 pixels

Currently, I am working on a Vue project that utilizes the Vuetify library. During my development process, I came across an unusual zoom jump between 1904px and 1903px. These sizes do not align with any predefined styles like md or lg. I am curious as to ...

Generate a new TreeView using the checked checkboxes from a current TreeView

I am currently working on implementing a dynamic user access feature for specific nodes within an existing treeview that is also dynamic. The primary TreeView that I am using contains checkboxes and gets populated from a database. Additionally, there is a ...

Retrieving the link to share for every video located in the Dropbox folder

My Dropbox folder contains a set of videos labeled "v1.avi, v2.avi, ....., vn.avi". I am looking to automate the process of extracting the share link for each video in the folder so that I can easily use it as a source value for HTML video. . . . Is ther ...

Dealing with callback errors: error handling is anticipated

In my Vue web application, I have enabled ESLint and encountered an issue with the following code: myApi.get('products/12').then((prodResponse) => { state.commit('ADD_PRODUCT', {product: prodResponse.data}) }, error => { cons ...

Extract source, medium, etc. data from __utmz GA with the help of JavaScript

Is it possible to retrieve the campaign, source, and medium that Google Analytics records all at once when the page loads? If so, could I use jQuery to look up the values from __utmz? ...