How to automatically insert a comma into numbers as you type in Vue.js

I am trying to insert separators in my numbers as I type, but for some reason it is not working.

Sample Code

<el-input-number v-model="form.qty" style="width: 100%;" id="test" placeholder="Quantity" controls-position="right" v-on:keyup="handleChange" :min="1"></el-input-number>

methods: {
    handleChange: function(value) {
        let vm = this;
        console.log(value);
        const result = value.toString().replace(/\D/g, "")
            .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            Vue.nextTick()
            .then(function () {
                vm.form.qty = result
            });
    },
}

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

Problem

Currently, when I enter numbers, no commas are added to the input field, however, when the values are sent to the back-end, they include commas.

Solution Needed

I actually need the opposite behavior from what I described earlier.

  1. Show numbers with commas in the user interface
  2. Send numbers without commas to the back-end

Any suggestions?

Answer №1

I believe the issue here is related to reactivity, consider using $set instead of = in your code.

handleChange(value) {
        console.log(value);
        let vm = this;
        let res = value.toString().replace(/\D/g, "")
            .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        console.log(res)
        this.$set(this.form,'num',res);

      }

Fiddle - https://jsfiddle.net/PratikPatel227/tLx3z96a/28/

when sending data remember to use - this.form.num.replace(/,/g, '')

Answer №2

I am not familiar with ElementUI, so I cannot guarantee that the el-input-number component will accept a formatted string as its value input. It is possible that the component internally removes all non-numeric characters from the value prop. However, the following solution is tailored for standard text inputs.

To display a different value than what is stored, you will need to break down the v-model directive into its original components. v-model actually combines binding the value and handling the @input event in one directive. You should keep the unformatted number in your form.qty field, but provide the el-input-number component with the formatted number through a computed property, like this:

<template>
  <!-- INSTEAD OF v-model, use :value and @input -->
  <el-input-number :value="formattedQty" @input="handleQtyInput" />
</template>

<script>
export default {
  data () {
    return {
      form: {
        qty: "0",
      }
    }
  },

  computed: {
    formattedQty () {
      // Add back commas to the string
      let qty = this.form.qty + ""
      return qty.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    }
  },

  methods: {
    handleQtyInput (newValue) {
      // Ensure the stored quantity is not formatted
      this.form.qty = newValue.toString().replace(/\D/g, "")
    }
  }
}
</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

What is the best way to incorporate a sidebar menu in an HTML webpage?

I am interested in creating a sidebar menu for my website using either HTML, CSS, or JavaScript. The W3 Schools website has a side menu that I find appealing and would like to create something similar. ...

Vue dynamic components fail to re-render within a v-for loop upon data changes

I've created a dynamic table component that allows me to modify columns by changing their ordering, adding new ones, or removing existing ones. The structure of my table body is as follows: <tr v-for="row in data" :key="row.id"& ...

Issue with Camera inversion not functioning properly in THREE.js with 1 Renderer and 2 Viewports

Check out this JSFiddle example In my project, I have a single scene with two cameras. Each camera is assigned to its viewport, and both viewports are placed side by side on the same renderer object. My goal is to have the second camera display a mirrore ...

Is it possible to create a looped GLTF animation in three.js using random time intervals?

I am currently exploring the world of game development with Three.js and have a specific query regarding animating a GLTF model. Is it possible to animate the model at random intervals instead of in a continuous loop? In the game I am creating, players wil ...

Executing a jQuery function only once per click on a select element - how can it be done?

I have a form with a select element, and I want some code to run when I click on it, but not when I choose an option. The issue is that the code is running twice, preventing me from selecting an option as it resets itself each time. Here is the HTML: &l ...

Prevent the execution of a Javascript function if it is already in progress

I've developed a function that retrieves records from a third party, and this function runs every 10 seconds. However, as I debug through Firefox, I notice a long queue of ajax requests. I'm contemplating including a statement that can signal to ...

What is the number of steps jQuery animates in?

Exploring my creative side, I decided to create my own custom animate function. Struggling to achieve a seamless animation effect, unlike the smooth transitions produced by jQuery. I'm curious about the formula they utilize to determine the ideal num ...

What is the reason behind WP AJAX consistently returning a value of 0?

Having trouble retrieving a proper response, as it always returns 0. Here is the JavaScript code in the head section: q = new XMLHttpRequest(); q.open('POST', ajaxUrl); q.onreadystatechange = function () { if (q.readyState === 4) { ...

How do I adjust the controls in Three.js to align with the previous camera position?

The three.js scene is equipped with W,A,S,D and left and right arrow controls, which allow for movement of the camera. However, the controls restrict the camera's movement to a fixed direction in the scene, rather than relative to its previous positio ...

Can you utilize the dotenv EJS file effectively?

I'm just starting out with Nodejs, so if I've made any mistakes, please let me know how to fix them... In my situation, I've stored all the credentials in a .env file and my index.ejs is attempting to extract this data. However, I encounter ...

What is the reason behind the failure of next/script with Google reCAPTCHA?

Currently, I am in the process of upgrading from next js version 8 to version 11. I wanted to take advantage of the amazing next js feature for "next/script". However, when I tried to implement it for Google reCAPTCHA using "react-recaptcha": "^2.3.10", th ...

maximum number of results in google custom search limit

I'm trying to retrieve the top 40 results from the Google API, but when I limit the result using the code below, it doesn't seem to work. How can I achieve getting the top 40 results with the Google API? <script> (function() { ...

Extract the color of an individual character

There is a code snippet in JavaScript using p5.js that functions as a video filter: const density = ' .:░▒▓█' //const density = ' .tiITesgESG' //let geist; let video let asciiDiv let playing = false let ...

Adding items to a JSON document

My task involves creating a pseudo cart page where clicking on checkout triggers a request to a JSON file named "ordersTest.json" with the structure: { "orders": [] }. The goal is to add the data from the post request into the orders array within the JSO ...

Unable to display SVG icon in Highcharts rendering

Is there a way to add a specific symbol in SVG format to a graph using Highcharts? Highcharts.SVGRenderer.prototype.symbols.download = function (x, y, w, h) { var path = [ "M19 5v14H5V5h14m1.1-2H3.9c-.5 0-.9.4-.9.9v16.2c0 .4.4.9.9.9h16.2c.4 0 ...

Importing a JavaScript file into another JavaScript file

var FS = require('fs'); var Path = require('path'); var Jsonfile = require('jsonfile'); var search = function () {}; search.prototype.projectContainerDirPath = null; /* * interface */ search.prototype.setPaths = function ...

Is there a way to transfer a value from one JS function to another in Node.js?

I am struggling to retrieve the return value from a JavaScript function in Node.js and pass it back in a POST method within my server file. Despite my efforts, I keep receiving an undefined result. What could be causing this issue? My objective is to retur ...

How can I make the lines of my drawer thicker in Material UI?

Currently, I'm in the process of implementing a left-side navigation bar for a web application I'm developing. The main challenge I'm facing is customizing the styles as desired when using the Drawer component. Specifically, I'm aiming ...

Error: Unable to render followers list due to incorrect data type

I have embarked on creating a unique Github user card generator that retrieves user data and their followers' information from the GitHub API, then displays them on a personalized user card. The follower's data received is in the form of an array ...

JavaScript functions flawlessly when run on a local machine, but encounters issues when transferred to a server

My JavaScript code is functioning perfectly on my local machine, but as soon as I upload it to my web server, it stops working. The website in question is www.turnbulldesigns.co.uk if you want to take a look. I have transferred the complete folder structu ...