Issue with the character count when using v-model in Vue CLI 3

Hey everyone, I'm new to Vue and could really use your assistance!

I am trying to count the number of characters in text inputs that contain only numbers using `v-model`. The goal is to display the character count as a variable. These inputs are generated dynamically inside elements from a `.json` file using `v-for`. Below is an example snippet from my App.vue:

<template>
    <div class="product-item" v-for="(product,index) in products" :key="product.id">
        <input type="text" v-model="coupon" @input='charCount()'>
        {{ couponCharCount }}
    </div>
</template>

<script>

import productsData from "../public/products.json";

export default {
    name: 'App',
    data() {
        return {
            products: productsData,
            coupon: '',
            couponCharCount: 0
        }
    },
    methods: {
        charCount() {
            // filter out non-numeric characters
            this.coupon = this.coupon.replace(/[^0-9.]/g,'');

            // count the characters
            this.couponCharCount = this.coupon.length;
        }
    }
}
</script>

The issue I'm facing is that when I input a value, it reflects across all `input` elements generated by `v-for`. What adjustments should I make to ensure each `input` works independently?

Thank you all in advance for any help you can provide!

Answer №1

To effectively manage all the input fields individually, it is crucial to maintain an array.

<template>
    <div class="product-item" v-for="(product,index) in products" :key="product.id">
        <input type="text" v-model="coupon[index]" @input='charCount(index)'> <!-- New adjustment -->
        {{ couponCharCount[index] ? couponCharCount[index] : 0  }} <!-- New adjustment -->
    </div>
</template>

<script>

    import productsData from "../public/products.json";
    
    name: 'App',
    data() {
        return {
            products: productsData,
            coupon: [], // Updated section
            couponCharCount: [] // Updated section
        }
    },
    methods: {
        charCount(index) {
            // Filtering for numbers only
            this.coupon[index] = this.coupon[index].replace(/[^0-9.]/g,''); // New adjustment

            // Calculating character count
            this.couponCharCount[index] = this.coupon.length; // New adjustment
        }
    }
</script>

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

Looking to have the text centered both vertically and horizontally within an <a> tag

I have a created an <a> element that links to JavaScript, but I want it to look like a button. <a href="javascript:void(0)" id="closebtn" onclick="closeNav()">&times;</a> Here is the CSS code: #closebtn ...

Expanding a collection of text inputs on-the-fly (HTML/JavaScript)

Looking to streamline our data entry process, I am developing an app for in-house tasks. Our team will be required to input information about various "items" that correspond to multiple "categories." To facilitate this task efficiently, I'm explorin ...

Why am I not receiving the expected feedback after submitting a request for a specific parameter in a Node.js and Express Router REST API?

Developed a Node module utilizing the Express router to facilitate the routes for the dishes REST API. Index.js file: const express = require('express'); const http = require('http'); const morgan = require('morgan'); const b ...

I would like to know more about the concept of getters and setters and how they can be effectively utilized

I've been struggling to understand the concept of getters and setters. Despite reading articles like JavaScript Getters and Setters and Defining Getters and Setters, I just can't seem to grasp it. Could someone please explain: The purpose of g ...

Encountering an error in Angular where the property 'nativeElement' is undefined when using @ViewChild

I have a div in my code named #map that will be displayed after a certain condition is met in a for loop. <div *ngFor="let message of fullMessagesArr"> <div *ngIf="message.replyMap"> <div #gmap style="width:100px;height:400px"></d ...

Issue with the reload animation jumping too quickly in Framer Motion on NextJS

While creating an animation for my landing page using NextJS with framer motion, I encountered a strange behavior after deploying the site. The animations started to happen too quickly and it felt a bit off. During development on localhost using Chrome, ev ...

"Step-by-Step Guide: Integrate Cloudinary Upload Widget with Angular Framework

Struggling with integrating the Cloudinary Upload Widget into my Angular project. I followed the example code provided by Cloudinary, but it's not functioning as expected. It seems like there's a missing import or package needed to access the clo ...

Using axios to pass parameters in a URL with the GET method on a localhost server

I need help using Axios to consume my Go lang API in my React front-end. The route for the API is localhost:1323/profile/email/:email/password/:password, but I'm struggling to figure out how to pass the email and password parameters in the Axios GET r ...

Can we dynamically apply a class to the body depending on the domain in the window's URL?

Currently, I am developing a website for a company that has operations in both New Zealand and Australia. They have domains pointed to the same website with both .co.nz and .com.au extensions. I have written the following code to assign the class "austral ...

Using AJAX to Interact with PHP

Currently, I am facing a problem with my PHP code where my For each loop is not properly waiting for the response of the AJAX call. I have attempted to incorporate Promise functions to solve this issue but unfortunately, it did not work out as expected. ...

Designing a user interface that consists of numerous distinct components

Challenge I'm faced with a dilemma regarding site A, which is built using React. Specifically, I need to find a way to integrate smaller React components into site A whenever a user navigates to a specific page within the site. Each of these smalle ...

Tips for extracting innerHTML or sub-string from all elements that have a specific class name using JavaScript

When it comes to shortening the innerHTML of an element by its Id, I have found success using either slice or substring. While I'm not entirely clear on the differences between the two methods, both accomplish what I need them to do. The code snippet ...

How to customize the center text of Chart.js doughnut chart

I've tried every search I can think of, but still can't find a solution to my problem. I want to customize the text in the middle of my doughnut chart (not tooltips). The chart is created using Chart.js and includes a percentage in the center. E ...

What is the best way to access the Vue instance within Vite?

Just diving into Vue 3 and Vite. How can I access the Vue instance? In the past, I would usually... import Vue from 'vue' However, in my Vue3/Vite project, there is no default export in the vue module, so when I try... Uncaught SyntaxError: The ...

Tips for testing the functionality of Webservices methods when they are invoked through AJAX requests

I am currently diving into Test-Driven Development (TDD) and I'm facing a challenge on how to properly unit test a webservice that is called in JavaScript via AJAX. Although I've researched methods for mocking the AJAX call and individually testi ...

Display nested array objects of varying levels within VUE

How do I display nested elements on the UI when dynamically generated based on a parent element's selected option (e.g. List)? For example, in the code below, when creating a field and selecting the List option, another nested should appear, and so o ...

Arranging a numerical array using a function

As someone who is brand new to coding and still getting the hang of Javascript, I've been taking some basic courses and trying out challenges on my own. Despite searching for an answer to my question, I haven't found anything quite like it. If an ...

When clicking to open the md-select on Angular Material 1.1.0, an unwanted [object object] is being appended

Every time I try to open the md-select input, an [object Object] (string) is added to the body tag. Click here to see the md-select input After clicking the md-select once, this is how the body looks ...

Exploring the depths of nested collections in Angular 12

As I work on my very first Angular/Firestore app, I find myself grappling with understanding how to retrieve data from nested collections. The Firestore database path that I need to access is as follows: /Customer(CollectionName)/cl0Apvalb6c0w9hltQ8AOTF4go ...

The functionality of AngularJS ng-model seems to be disrupted when it is set within a directive

Is it possible to automatically generate the ng-model of an input based on the name of the input itself? This requirement arises from using Html.TextBoxFor in MVC, which creates the necessary name for binding the input to the server-side model. To streamli ...