Automatically insert a comma for type=number in VueJS

Is there a method available to automatically insert commas into an input type="number" field in vue js? I need this functionality to trigger the IME options in Microsoft and prevent users from inputting Japanese characters.

<ui-textbox label="initial" v-model="initial_cost"
    name="initial_cost"
    v-validate="`numeric|decimal`"
    type="number"
    v-on:keydown="isNumber"
    :maxlength = "18"
    :enforceMaxlength="true"
    value = 0.00
    format="number"
></ui-textbox>

isNumber: function(evt) {            
        evt = (evt) ? evt : window.event;
        var charCode = (evt.which) ? evt.which : evt.keyCode;
        var charval= String.fromCharCode(evt.keyCode);
        console.log(typeof evt);
        if((charCode >= 48 && charCode <= 57) || (charCode >= 96 && charCode <= 105) || charCode == 8 || charCode == 46 ||
        charCode ==36 || charCode ==35){                
            return true;
        }else{
            return false;
        }

If the user enters 1000, the display should show 1,000, 10000 as 10,000, and so forth. I came across a solution to a similar issue here, but it seems like they are using an input type="text" field. Is there a way to implement this for my type="number" field in vue?

Answer №1

After some discussion in the comments above, it has been noted that adding a comma to an input with type="number" is not feasible. Only when the input is set as type="text" can the comma be displayed.

To address this issue, one solution is to dynamically change the input type from number to text on focus and blur. This way, users will only be able to enter numbers, and the comma will appear once they have finished typing.

A new reactive variable called inputType can be added to the data section:

  data() {
    return {
      inputType: "text"
    };
  }

Update or add attributes in the ui-textbox component:

<ui-textbox /*...*/ :type="inputType" @focus="inputType='number'" @blur="inputType='text'">
    <!-- ... -->
</ui-textbox>

This approach makes the type attribute dynamic - switching to number on focus and back to text on blur.

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

Enhancing the "click-to-pause" feature with jQuery Cycle

Is it possible to delay the click-to-pause feature on my slideshow until after the first slide transition? Currently, the slideshow becomes clickable as soon as the DOM is ready, which is too early for my liking. Here is a simplified version of my current ...

Genvalidator: Validate forms by checking for checkbox selection

Currently, I am utilizing genvalidator to conduct tests on input fields within a form. One issue I am encountering is the inability to determine if a checkbox has been checked. Below are the settings for all fields: frmvalidator.addValidation("name","req ...

Steps to creating a nested function

I'm still learning the ropes of Javascript, and I've been working on creating a personal library to streamline my coding process. Here's the code snippet I've come up with. function myLibrary() { let _this = this; this.addString = ...

AngularJS $cookies version 1.6.9 experiencing functionality issues

I recently implemented AngularJS $cookies 1.6.9 in my website to handle cookie management. To test it out, I attempted a basic cookie set like this: $cookies.put('myCookieTest', 'test'); var cookie = $cookies.get('myCookieTest&apo ...

Unlocking the secrets of integrating Vuex store with JavaScript/TypeScript modules: A comprehensive guide

I am working on a vue application and I have a query. How can I access the store from javascript/typescript modules files using import/export? For example, if I create an auth-module that exports state, actions, mutations: export const auth = { namesp ...

Combining multiple arrays of arrays in JavaScript

I am dealing with an array that contains nested arrays. This particular array is called template https://i.sstatic.net/QIs0Q.png template consists of 2 arrays, but the number can vary and there can be multiple levels of arrays within each one. Here' ...

Is it possible to move between textboxes using arrow keys in HTML?

Is there a way to navigate through textboxes using arrow keys in HTML without relying on jQuery? Possibly utilizing JavaScript, HTML, CSS, or another method? Thank you for your help! <body> <form> <input type="text"&g ...

Using jQuery to select elements with specific innerHTML values

$('.select option:selected[innerHTML="5"]') In this case, I am attempting to choose an option that is currently selected and has innerHTML that perfectly matches a specific string (for example: "5") For reference, here is a fiddle link: http:// ...

Drag and Drop in Angular with Dragula - Trigger Confirmation on Drop Event

I need to implement a confirm modal dialog (UI Kit) when an element is dragged into a new bag using angular 1.4.8 and angular-dragula. If the user clicks ok, the process should continue, but if they click NO, the element should return to its original bag. ...

Iterate through HTML content and utilize JavaScript along with Regular Expressions to substitute specific strings

In my HTML located in Anki, I have the following structure: <p>[!Quote] Title of callout 1<br>Content of callout 1</p> <p>[!Quote] Title of callout 2<br>Content of callout 2</p> <p>[!Quote] Title of callout 3<br ...

Do we need to use parseInt for the '*' operator in JavaScript?

I have an array where I am mapping it at some point to calculate the sum and percentages. However, when I tried implementing the logic, I noticed that using '*' directly works fine but using '+' adds the two strings together. For exampl ...

AngularJS - encountering a 404 error when reloading the page after removing the Hashbang

After taking out the hashbang from my routes by using $locationProvider.html5Mode(true); Now, when I go to a page like "domain.com/download", it works. But if I refresh this same page, I get a 404 Error. URLs like "domain.com/download" can only be acce ...

When using the v-for directive with an array passed as props, an error is

I encountered an issue while passing an array of objects from parent to child and looping over it using v-for. The error message "TypeError: Cannot read property 'title' of undefined" keeps appearing. My parent component is named postsList, whil ...

Delivering Background Videos with Node.JS

Apologies if my question seems off base or confusing, as I am not very knowledgeable in the world of nodejs. I have been comfortable using just plain PHP and Apache for a while until I discovered ZURB Foundation's stack with Handlebars and SASS, along ...

Verify your identity using Google reCaptcha during Passport authentication

I am currently working on integrating google reCaptcha into my signup form's back-end, which already includes passport authentication. The code I have so far looks like this: app.get('/signup', function(req, res) { // render the ...

css problem with scaling in firefox

My goal is to create a website that adjusts its size based on the document size. When the document size is between 0px and 1024px, I want the design to be responsive. This can easily be achieved with CSS media queries. Similarly, when the document size is ...

Using grid-template-areas in ReactJS function components does not function as expected

REMINDER: Check out and customize the code in CodeSandbox. This is a parent component with 5 children elements. Among them, 3 are React components and the remaining 2 are regular HTML buttons: import "./App.css"; import React from "react&qu ...

I am having difficulty retrieving all the cssRules for certain pages

Attempting to retrieve all CSS rules using JavaScript has yielded varying results. For instance, on StackOverflow, the code used is: console.log( document.styleSheets[1].href,'rules', document.styleSheets[1].cssRules,'Should be css rules, ...

The E.js Template encountered an error with an unexpected token "else"

I am in the process of creating a website quickly using e.js & Express. However, I am encountering some problems when trying to use an if-else statement within e.js tags. The if statement works fine, but as soon as I add an else statement, things start t ...

Executing code only after the completion of the .ajax function (outside of the .ajax function)

Working with an API, I successfully implemented the .ajax function but now need to access the data outside of that function. Attempting to use jQuery's .done function for this purpose has proved unsuccessful so far. Despite trying different solutions ...