Tips for achieving accuracy with two decimal points and improving the input process

I implemented code that utilizes the vuejs watch property on reactive inputs. You can check out the code by following this link:

When entering values in the 'percentage' input, it recalculates the value as expected due to watching, causing some jittery behavior. Is there a way to achieve this without using a timeout and maintain a precision of two decimals? The input process should be smooth without any sudden jumps. This issue seems to occur with certain inputs, for example, entering '7' in the 'percentage' input shows strange behavior. The same problem also arises with the computed components.

The code snippet is provided below:

<script setup>
import {reactive, watch} from 'vue'

const data = reactive({
  first : 50000,
  second : 20000,
  percentage : ''
})

watch(() => data.percentage,
    (newValue, oldValue) => {
        data.second = (data.first*newValue)/100

    }
)

watch(() => data.second,
    (newValue, oldValue) => {
        data.percentage = (newValue/data.first)*100

    }
)
</script>

<template>
  <div>

  <div>
  <label>First</label>
  <input type="text" v-model="data.first">
  </div>

  <div style="padding: 15px 0px">
  <label>Second</label>
  <input type="text" v-model="data.second">
  </div>

    <div>
  <label>Percentage</label>
  <input type="text" v-model="data.percentage">
  </div>
  </div>
</template>

Answer №1

In my opinion, it is not advisable to create two watches that will constantly update each other's values as this could lead to multiple triggers.

Instead, I suggest utilizing a function that executes when there is user input.

<script setup>
import {reactive, watch} from 'vue'

const data = reactive({
  first : 50000,
  second : 20000,
  percentage : ''
})

const handlePercentage = () => {
  data.second = (data.first*Number(data.percentage))/100

}

const handleSecond = () => {
  data.percentage = (Number(data.second)/data.first)*100
}
</script>

<template>
  <div>

  <div>
  <label>First</label>
  <input type="text" v-model="data.first">
  </div>

  <div style="padding: 15px 0px">
  <label>Second</label>
  <input type="text" v-model="data.second" @input="handleSecond">
  </div>

    <div>
  <label>Percentage</label>
  <input type="text" v-model="data.percentage" @input="handlePercentage">
  </div>
  </div>
</template>

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

Webpack failing to load jQuery correctly

In the process of transitioning my application.js application into smaller page bundles using SplitChunks, I have encountered a situation in my users/show.html.erb page where I am utilizing the following tag to import the specific chunk. <%= javascript ...

Has Next.js incorporated a maximum cache size feature along with an invalidation algorithm like LRU?

Currently, I have a Next.js site that utilizes getServerSideProps for data fetching. However, I am interested in switching to getStaticProps and implementing incremental static regeneration (ISR) for improved performance. Currently, my memory usage is ap ...

Evaluating Two Records Displayed On Screen Using JavaScript

Currently seeking a method to visually compare 2 JSON records on the screen. Ideally, I would like to display these records side by side and highlight any matching or mismatched properties. Are there any existing libraries that offer this functionality? I ...

Creating a script to randomly target a player with a monster in javascript

My latest project involves developing a game using Vue.js with characters like tank, DPS, and healer. data: { tankHealth: 100, healerHealth: 100, dpsHealth: 100, monsterHealth: 200, gameRunning: false, turns ...

Leveraging 2-dimensional indexes in collaboration with the $geoNear operator

I encountered an issue while attempting to use geoNear with aggregate as I received the following error message: errmsg: "'near' field must be point" The reason for this error is because my location field is represented as [Number]: var locati ...

How can I correctly parse nested JSON stored as a string within a property using JSON.parse()?

I am having trouble decoding the response from aws secretsmanager The data I received appears as follows: { "ARN": "arn:aws:secretsmanager:us-west-2:0000:secret:token-0000", "Name": "token", "VersionId&qu ...

Node.js Monitoring Statistics Displayed in Command Line Interface

Apologies if this question has been asked before. I have been looking for something similar to what I need, but haven't been able to find it anywhere. So, I thought I'd ask. I am working with a nodejs script using puppeteer and I want to view st ...

Unable to substitute a value using the useState hook in React

Whenever I click a key, I attempt to update the value of a variable but it appears not to be working as intended. ↓ The current implementation is not effective and needs improvement import React, { useState, useEffect } from 'react'; const Li ...

Mastering server requests in Angular 5

I have come across recommendations stating that server requests should be made via services and not components in order to ensure reusability of functions by other components. Ultimately, the server response is needed in the component. My query pertains t ...

The inefficiency of invoking Jquery on elements that do not exist for the purpose of caching

What is the impact if JQuery attempts to access elements that do not exist? Will there be any significant CPU overhead other than script loading? Does it matter if this is done for a class or an id? For optimization purposes and to minimize simultaneous c ...

Concealing information beneath a veil of darkness

I'm looking to implement a solution using JS/CSS/HTML5 to hide content within a div container with a shadow effect. The end result should resemble the example image I've provided. Additionally, I'd like the ability to customize the color of ...

FullCalendar is encountering loading issues when trying to fetch data from JSON, with the

I am currently utilizing FullCalendar to create a schedule for theater rehearsals. After considering my options, I concluded that JSON would be the most efficient way to retrieve events from my MySQL database. In the JavaScript code for the calendar page, ...

Is it possible for variables in Javascript to not be defined in time?

Recently, I've been diving into the fascinating world of asynchronous JavaScript. It's intriguing to me how certain functions can take varying amounts of time to complete. As an example, I often create a promise to handle tasks that require wait ...

Execute the cucumber cli programmatically in the index.js file of a node application

Recently, I received an automation framework built in CucumberJS and Node with Selenium. However, the framework is using an outdated version of Cucumber that relies on promises. Wanting to take advantage of the latest synchronous step feature, I decided to ...

The disappearance of ngx-charts lines is observed when the chart is rendered within a PrimeNG dialog that gets closed and reopened

In my TypeScript Angular application, I am currently incorporating PrimeNG. Specifically, I am utilizing the dialog component from PrimeNG to display charts using ngx-charts, specifically the ngx-charts-line-chart module. Initially, when I open the dialo ...

When using sequential jQuery 'pages', an error referencing the third frame occurs

I am new to using javascript/jquery and have been experimenting with the w3schools tutorials and jquery documentation. I created a page where user input is accepted and javascript prints output based on that input. I tried modifying it to work sequentially ...

Counter is effective for the initial post, yet it does not function properly for the subsequent post

Can anyone help with an issue I'm having with my JavaScript counter? It works for the first comment, but not the second one. This problem persists whether I use PHP or JavaScript. Below is the JavaScript code for the counter: var count = (function() ...

React JS issue with SVG linearGradient not displaying accurate values

Within my component, I am working with SVG paths and a linearGradient value passed down from the parent component through static data. The properties 'startColor' and 'stopColor' are used to define the gradient colors for each element. ...

Prevent redirection when submitting and show an error message instead

I implemented a login system where, upon entering the correct username and password, a token is stored in local storage. If there's an error with the credentials, an "Login Unsuccessful" message is displayed. Everything was functioning correctly until ...

Adding a custom button to every row in a Vuetify datatable with Vue: What's the best way to do it?

Just getting started with Vue and trying to work with datatables. I'm currently using Vuetify's datatables to create a component that, upon page load, makes a request to my backend, fetches some data, and displays that data in a neat datatable fo ...