A handy Vue.js function

I'm currently working on creating a utility method in Vue.js to validate decimal numbers from any input field, but I am facing difficulty in persisting the value internally within Vue.js.

In the past, when using jQuery, I used this approach:

$('body').on('blur', '.decimal', function() {
    var val = $(this).val();
    if ($.isNumeric(val)) {
        val = parseFloat(val).toFixed(2);
        $(this).val(val);
    } else {
        $(this).val('');
    }
});

Although in Vue, my implementation seems to be overwriting the value without storing it internally as intended.

function isNumeric(n) {
    return !isNaN(parseFloat(n)) && isFinite(n);
}
methods: {
    validateDecimal: function (e) {
        var val = e.target.value;

        if (isNumeric(val)) {
            e.target.value = parseFloat(val).toFixed(2);
        } else {
            e.target.value = '';
        }
    }
}

HTML

<input class="ui-input" :value="some.value" placeholder="0.00" @blur="validateDecimal">
<input class="ui-input" :value="some.othervalue" placeholder="0.00" @blur="validateDecimal">
<input class="ui-input" :value="another.dynamic.input" placeholder="0.00" @blur="validateDecimal">

Answer №1

It appears that passing the data object reference to the handler method is possible in this way: (Note, it's important not to just pass the data property alone as it may not act as a reference.)

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    inputs:{
      'v1':{
        value:'1.256'
      },
      'v2':{
        value:'1.521'
      }
    },
    someInput:{value:'1.7125'}
  },
  methods:{
    validateDecimal: function (obj, prop, event) {
        console.log('validateDecimal', obj);
        var value = event.target.value;
        console.log(value);
        if (Number(parseFloat(value)) === value) {
            value = parseFloat(value).toFixed(2);
            this.$set(obj, prop, value);
        } else {
            this.$set(obj, prop, '');
            event.target.value = '';
        }
    },
    foo: function(){
      console.log(this.inputs.v1.value)
      console.log(this.inputs.v2.value)
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="item,key in this.inputs">
    <input class="ui-input" :value="item.value" placeholder="0.00" @blur="validateDecimal(item, 'value', $event)">
  </div>
  <div>
    <input class="ui-input" :value="this.someInput.value" placeholder="0.00" @blur="validateDecimal(someInput,'value', $event)">
  </div>
  <button @click="foo">Click</button>
</div>

Edited by the original poster: Added an additional parameter for the name of the property and utilized $set to ensure reactivity of dynamic properties. This enhancement aims to make the method more versatile for handling various dynamic input fields with any property name.

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

Middleware in Express that requires asynchronous initialization

As I develop express middleware that will interact with a database, I aim for it to be self-contained within a package. One concern I have is how to handle the database connection efficiently. Since it is an async operation and only needs to occur once dur ...

Bottom-aligning text in Tailwind CSS

Creating two <p> tags to store text: <p v-if="my_property <= 0" class="text-green-500 text-lg font-bold">{{Math.abs(my_value)}}%</p> <p v-else class="text-red-500 text-lg font-bold">{{my_value}}%< ...

Example of Utilizing Google Places API

The Issue I've been struggling to make this google maps API example function correctly. Even after directly copying the code from Google's website, the example fails to display properly. For instance, the map doesn't show up, the search bar ...

Guide to retriecing a state in Next.js 14

Check out my code below: "useState" // firebase.js import firebase from "firebase/app"; import "firebase/auth"; // Import the authentication module export default async function handler(req, res) { if (req.method !== " ...

Table template incompatibility detected with Bootstrap

I have been attempting to recreate a template using a table as my foundation, but simply copying the code does not yield the same results. For reference, here is the table template I am using: Below is the code I have copied and pasted into my index.csht ...

Barba.jS is causing a delay in loading scripts after the page transition

One of my index files includes Gsap and Barba JS, while an inner page includes additional JS files such as locomotive.js and OWLcarousel.js. These two JS files are not necessary for the index page. However, when transitioning from the index page to the inn ...

Display image URL data in a pop-up box when the button is clicked without dimming the background

In my quest to access the legend of a WMS layer in Openlayers 3, I have successfully obtained the legends of the layer. However, I aim to display them in a popup box with a movable and close button. Below is the content of the .html page: <label>&l ...

Using GraphQL to verify the existence of a transaction within the blockchain

Even though I have a transaction ID, there are instances where it may take some time for a monetary transaction to appear on Blockchains. My approach involves using GraphQL to access the blockchain by querying it with the transaction ID. A return of &apos ...

How come TypeScript remains silent when it comes to interface violations caused by Object.create?

type Foo = { x: number; }; function g(): Foo { return {}; // Fails type-check // Property 'x' is missing in type '{}' but required in type 'Foo'. } function f(): Foo { return Object.create({}); // Passes! } functio ...

save the received data to a new document

How can I pass the data returned from the API below to another function in a separate JavaScript file? This question may be similar to others, but those do not involve working with returned results. Please consider this before labeling it as a duplicate. ...

Deciphering the occurrence of jQuery-Mobile page firing events: the mystery behind dialog pages appearing upon closure

I'm still fairly new to jQuery-Mobile and I'm trying to wrap my head around what exactly happens when a page or dialog is loaded. To help illustrate the confusion I'm experiencing, I put together a small collection of files that showcase th ...

I'm facing issues with Webpack not being able to resolve and locate the node

Encountering difficulties while setting up and running the Three.js library as a module based on the guidelines provided in the manual at Here is a summary of the steps taken: Created package.json npm init Installed webpack npm i --save-dev webpack we ...

Enhancing User Experience with Bootstrap V5 Form Validation and Sweetalert2: Displaying a Message of Success Upon Successful Submission

I am currently working on implementing a simple form using Bootstrap 5 that includes validation. My goal is to display an alert message when the form field is successfully submitted using Sweetalert2. Below is the code I have: HTML <form action=&q ...

What could be causing my jQuery to malfunction after I include the .sqrt() function?

Seeking assistance in creating a grid of divs, I am working on finding the square root of the user's input to determine the height and width required to form a square. The code below is what I currently have: $('#size').click(function(){ $ ...

Donut and Bar Graph by Highchart

My goal is to create a chart similar to the one shown in the Example Image linked below. I have provided two separate plunkers for each type of chart. What I am aiming for: Example Image Donut Chart: ===> Refer to Comment section for Plunkr link // ...

Enhancing middleware chaining in Express

Below is the code for my Express configuration: var server = express() .use(express.cookieParser()) .use(express.session({secret: buffer.toString('hex')})) .use(express.bodyParser()) .use(express.static('./../')); serv ...

Is it feasible to determine the specific memory address of an Object in a program?

Is it possible in JavaScript to determine the memory location and memory usage of an object? Any assistance on this matter would be greatly appreciated. ...

What is the best way to incorporate an exception for the printThis() element?

Is there a way to exclude a specific div from being printed when using the printThis() function? For example: <div id="print-it"> <div>hello</div> <div id="no-print-this"> <button>must be show on page but not print</but ...

The challenge of Angular form data binding

I'm encountering an issue with binding an input box to a controller in Angular. Despite following tutorials, the model never updates when I access the property or check the scope using AngularJS Batarang. Upon form submission, $scope.licenceKey remai ...

Tips for updating property values when calling a TypeScript function

Hello everyone, I am looking to convert a snippet of JavaScript code into TypeScript. JavaScript function newState(name){ var state ={ name : name, age : 0 } return state } function initStates() { this.JamesStat ...