Increase or decrease values in an input field using Vue3 when typing

I am looking to implement a feature where users can input numbers that will be subtracted from a fixed total of 100. However, if the user deletes the input, I want the difference to be added back to the total of 100. Despite my attempts, the subtraction works fine but the addition does not when figures are deleted:

Here is the code snippet I have tried using HTML and JavaScript:

                <input
                  type="number"
                  placeholder="Ex: 40"
                  v-model="e"
                  @keyup="validate()"
                  @blur="validate()"
                  required
                />

JS:

const total = ref(100);
const e = ref("");

    const validate = (e) => {
            if(e.value){
        totalPercentages.value = total.value - e.value
      }
    };

Answer №1

Here is a helpful tip: Utilize @blur() for accurate calculations.

To illustrate the concept, I have provided a code snippet using Vue version 2.

Check out the Live Demo below:

new Vue({
  el: '#app',
  data: {
    e: null,
    total: 100
  },
  methods: {
    validate() {
      this.total = 100;
      if (!this.e) return;
      if (this.e <= this.total) {
        this.total = this.total - this.e;
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input
         type="number"
         placeholder="Ex: 40"
         v-model="e"
         @blur="validate()"
         required
         />

   <span>Total : {{ total }}</span>      
</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

My PHP script is not functioning correctly with Ajax

I am currently working with HTML5, PHP, and JavaScript. My goal is to implement Ajax in order to display the sizes of a selected product when an option is chosen from #productoSeleccionado. However, I believe that there may be an issue with my code as the ...

The elements within the Popup Modal are not displaying as expected

I found a helpful tutorial that teaches how to display a Popup Modal Window when the page loads. However, I'm facing an issue where the modal is not showing the contents and images properly. The code I am working on can be found at jsFiddle. My goal ...

Showing the output variable from node.js on a canvas

Is it possible to display the output of my node.js program, which consists of a series of points (x,y), on canvas without a browser? I came across this module that could potentially help with displaying the points: (https://www.npmjs.com/package/canvas) ...

Displaying a dynamic splash screen during the resource-loading process on an Android application

I would like to implement an animated image (currently using a set of PNGs) as a splash screen while my resources are loading. I have successfully displayed the splash screen using this method. However, the issue I am facing is that the splash screen appe ...

Tips for safely executing an SQL query with electron.js

I have a new project where I need to interact with an SQL database on the local network, but it's not located on the same system I'm working on (not SQLExpress). So far, I've figured out how to collect user input on a webpage and send that ...

Leverage videojs-vr within a Vue.js component

I have been experimenting with integrating the videojs-vr package, which I installed through npm, into a Vue.js component. However, I encountered an error: TypeError: videojs is not a function at VueComponent.mounted (VR.vue?d2da:23) at callHook (vue.esm. ...

What is the best way to store changing images in a Next.js application?

Is it possible to set the cache-control for images in a list of objects received from an API? Each object in the list contains a property called imageUrl, which is the link to the image. ...

Navigating global variables and functions in Vue3 with TypeScript

Feeling lost in the world of Vue.js, seeking guidance here. Attempting to handle global data and its corresponding functions has led me on a journey. Initially, I experimented with declaring a global variable. But as more functions came into play, I trans ...

Withdrawal of answer from AJAX request

Is there a way to create a function that specifically removes the response from an AJAX call that is added to the inner HTML of an ID? function remove_chat_response(name){ var name = name; $.ajax({ type: 'post', url: 'removechat.php ...

Transferring SQL server dates to jQuery Calendar through AJAX communication

I am currently working on implementing a jQuery calendar example, and I want to load the dates from my SQL database instead of using hardcoded values. I am considering using Ajax post to send a request to my web method and retrieve the data. However, I am ...

Vue.js - Maintaining input value when model declines updates

I am working on a text input that allows users to enter numbers with a maximum of three digits after the decimal point: <v-text-field type="text" :value="num" @change="changeNum($event)" /> <p>{{ num }}</p> ... export default { data: ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...

A guide to extracting text from HTML elements with puppeteer

This particular query has most likely been asked numerous times, but despite my extensive search, none of the solutions have proven effective in my case. Here is the Div snippet I am currently dealing with: <div class="dataTables_info" id=&qu ...

Trouble arises when managing click events within the Material UI Menu component

I've implemented the Menu Component from Material UI as shown below - <Menu open={open} id={id} onClose={handleClose} onClick={handleClick} anchorEl={anchorEl} transformOrigin={{ horizontal: transformOriginRight, vertical: t ...

several different objects within the rightIconButton of a ListItem component in MaterialUI

I am currently working on a project where I need to add multiple elements to the rightIconButton of a ListItem. The tools I am using are Material UI v0.20 and [email protected] <ListItem rightIconButton={ <span> ...

Versatile accordion with separate functionalities for items and panels

When I have different functions for clicking on item and title, clicking on the item works fine but clicking on the panel triggers both functions. Is there a way to resolve this so that I can click on the item using Function_1 and click on the panel using ...

Method in Vue.js is returning an `{isTrusted: true}` instead of the expected object

I am having an issue with my Vue.js component code. When I try to access the data outside of the 'createNewTask' function, it renders correctly as expected. However, when I attempt to log the data inside the function, it only returns {isTrusted: ...

Troubleshooting a problem with jQuery waypoints in a static HTML/JS

Utilizing waypoints and windows to display the panels similar to the fiddle example I have created: http://jsfiddle.net/6bMMa/1/ Everything is functioning correctly, however, I have only managed to make it work by using id numbers on the panel divs. The ...

Conceal elements with a single click of a button

How can I use jQuery to hide all li elements with an aria-label containing the word COMPANY when the Search from documents button is clicked? Here is the HTML code: <ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content" id="ui-id-1" t ...

Vertical alignment of content over image is not in sync

I am attempting to center my div container .home-img-text vertically in the middle of its parent div .home-img. Despite trying various methods such as setting .home-img-text to position: absolute, relative, adding padding-top, and several others, I haven&a ...