Convert the numerical values from an array into an input field format

Currently, I have two inputs and an array with two number positions. The v-model in each input corresponds to a value in the array. Whenever a change is made in either input field, it reflects on the corresponding position in the array, which works perfectly.

My goal is to format the numbers in each input by adding thousands and millions commas while still keeping the original unformatted number in the array as a type of number. Despite having a function that formats the number correctly in the console, I am struggling to display this formatted value in the input fields. How can I accomplish this task?

<template>
  <input 
    type="text" 
    class="text-center" 
    v-model="rangePrice[0]"
  /> 
  <input 
    type="text" 
    class="text-center" 
    v-model="rangePrice[1]"
  />
</template>

<script setup>
const rangePrice = ref([0, 100000000])

// This function successfully formats the value in the console
const format = (e) => {
  console.log(rangePrice.value[0].toString().replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","))
}
</script>

In my implementation, I am utilizing a Vue form slider where there are two draggable points representing the minimum and maximum values from the array. As the slider is dragged, the numeric values are updated accordingly:

<Slider
 class="slider"
 v-model="rangePrice"
 :lazy="false"
 :min="0"
 :max="100000000"
 :tooltips="false"
/>

Answer №1

Consider using @input and :value instead of v-model in this scenario:

const { ref } = Vue
const app = Vue.createApp({
  setup() {
    const rangePrice = ref([0, 100000000])
    const formatInput = (e) => {
      return e.toString().replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    }
    const updateInputValue = (e, index) => {
      rangePrice.value[index] = parseInt(e.target.value.replaceAll(',', ''))
    }
    return {
      rangePrice, formatInput, updateInputValue
    };
  },
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <input 
    type="text" 
    class="text-center" 
    :value="formatInput(rangePrice[0])"
    @input="updateInputValue($event, 0)"
  > 
  <input 
    type="text" 
    class="text-center" 
    :value="formatInput(rangePrice[1])"
    @input="updateInputValue($event, 1)"
  > 
  {{rangePrice}}
</div>

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

jQuery can be used to obtain the label for a checkbox with a particular value

Currently, I am facing an issue with retrieving the label for a checkbox using jQuery. Let me provide you with the relevant HTML code: <div class="checkbox"> <label><input type="checkbox" name="cb_type[]" value="sold" >Sold</label ...

Express.js experienced a 404 error when processing POST requests

When working with js and express, the route handler file looks like this: var express = require('express'); var passport = require('passport'); var authRoutes = App.route('authRoutes'); va ...

Tips for implementing a condition such as "greater than or equal to" in the filtering search feature in Vue.js

Hey everyone, I need help with building a real estate application. I want to add a condition in the Bedrooms filter function where it filters properties greater than or equal to a selected number. For example, if I select 2 on the Bedroom list, I want the ...

Can anyone tell me what I might be doing incorrectly when comparing these two timestamps?

I am facing an issue while comparing two timestamps in Angular. Here is the code snippet: public isAuthenticated(): boolean { const token = localStorage.getItem('Fakelife'); const lifetime = new Date().getTime(); const result = life ...

Is there a way to ensure that my AngularJS factory fetches HTTP data only once?

I have implemented a factory in my project to share data among multiple controllers. Here is the code for my factory: var szGetData = "some url that works"; myApp.factory('Data', function ($http) { var eventData = {}; eve ...

"Exploring the Possibilities with WordPress and Waypoint Js

After exploring various resources and tutorials online, I am struggling to implement Waypoints with WordPress. Despite placing the necessary files like waypoints.min.js and waypoints.js in the designated download folder within the js directory of my templa ...

Tips for utilizing javascript document.createElement, document.body, and $(document) in an HTML web resource for Microsoft CRM code reviews

Let me start off by saying that I am not a regular blogger and I am feeling quite confused. If my question is unclear, please provide guidance for improvement. I recently submitted a Microsoft CRM PlugIn to the Microsoft Code Review. I am new to Javascrip ...

My ReactNative Android application is experiencing significant lag, is there anyone who can assist me in resolving this issue?

Currently, I'm tackling a reactnative android app project and have noticed a significant drop in performance. Unfortunately, I am clueless about the root cause of this issue. Could it be related to the navigator or are there other underlying factors a ...

Downloading Laravel Excel Files via an Ajax Call

Is it possible to generate an Excel file using Laravel with PHPSpreadsheet (PHP lib) and then send the XLSX file to the frontend for download? JSX Section axios .get( "/excel/export/dashboardTable", {} ) .then(resp => { //success call ...

Warning: React Element creation caution with flow-router integration

Whenever I incorporate the following code into my Meteor app: Home = FlowRouter.route("/", { name: "App", action(params) { ReactLayout.render(App); } }); An error message pops up in the Chrome console: Warning: React.createElement: type shoul ...

Numerous criteria for selecting a checkbox

I am working with a student database table called student_db, which looks like this: Name Gender Grade City John Male 2 North Dave Male 4 North Garry Male 3 North Chirsty Female 5 East Monica Female 4 East Andrew Male ...

The split function in JavaScript is exhibiting some unusual behavior

There is something wrong with my code challenge1 = () => { var data = fs.readFileSync('santa21.txt', 'utf8'); data = data.toString(); dataSplit = data.split(' ') console.log(dataSplit); }; challenge1(); The result of the ...

Browsing through a jQuery JSON object in Chrome reveals a dynamic reshuffling of its order

Jquery + rails 4 Within the json_data instance, there is data with key-value pairs. The key is an integer ID and the value is an object containing data. However, when attempting to iterate over this data using the jQuery $.each function, the results are s ...

Constructor not executing when using Object.create

Attempting to instantiate a class within a static method, I am using Object.create(this.prototype), which appears to be functioning correctly. Nonetheless, when I check the console, my property items is showing as undefined. The base class called model lo ...

The function iframe.scrollTo() is not effective for scrolling through Excel or PowerPoint documents on an iPad

I am trying to create a custom scrolling feature for iframe content specifically for iPad. Currently, I have set up my iframe like this: <div id="scroller" style="height: 300px; width: 100%; overflow: auto;"> <iframe height="100%" id="iframe" ...

The resizing of iframes in Javascript is malfunctioning when it comes to cross-domain functionality

I have implemented a script to dynamically resize iframe height and width based on its content. <script language="JavaScript"> function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newheight=docume ...

Unable to loop through a list in JavaScript

<script type="text/javascript"> window.onload = function () { for (var i=0;i<@Model.listsinfo.Count;i++) { $('#work').append($('<div class="col-md-3" id="temp"><label for="tex ...

Add the child element to the $slot.default

I have a situation where I need to implement a custom modal in my component but I am not sure where to place the dialog content. To tackle this issue, I came up with the following approach: <template> <div class="ComponentItself"> ...

SweetAlert2 not displaying properly in Ionic6 - troubleshooting the issue

My current project is an Ionic 5 Angular project with SweetAlerts2 popups. Recently, I decided to upgrade to Ionic6 and encountered an issue where the SweetAlerts2 popups are not displaying correctly. The alert seems to only show up in the header, leaving ...

jQuery - harnessing the power of JavaScript events such as "dragover"

I have a JavaScript function that includes an event listener for 'dragover'. Here is the code snippet: document.getElementById("someID").addEventListener("dragover", function(){ //Add your logic here }, fa ...