0

I am using the following code for price entry with vue js, but it does not give the output I want. and I want to cancel from keyboard keys (POINT). only the comma will work. By the way, I'm new among you, I would be happy if you can help me accordingly.

Sample: 0,00 1.000,00

Code

Vue.component('my-currency-input', {
    template: `
        <div>
            <input type="text" v-model="formattedCurrencyValue" @blur="focusOut"/>
        </div>`,
    data: function() {
        return {
            currencyValue: 0,
            formattedCurrencyValue: "0.00"
        }
    },
    methods: {
        focusOut: function() {
            // Recalculate the currencyValue after ignoring "$" and "," in user input
            this.currencyValue = parseFloat(this.formattedCurrencyValue.replace(/[^\d\.]/g, ""))
            // Ensure that it is not NaN. If so, initialize it to zero.
            // This happens if user provides a blank input or non-numeric input like "abc"
            if (isNaN(this.currencyValue)) {
                this.currencyValue = 0
            }
                        // Format display value based on calculated currencyValue
            this.formattedCurrencyValue = this.currencyValue.toFixed(2).replace(/(\d)(?=(\d{3})+(?:\.\d+)?$)/g, "$1,")
        },
    }
});

new Vue({
    el: '#app'
});

Liza
  • 129
  • 1
  • 8
  • Instead of fighting user input by blocking a few keys (which could be perceived as an app malfunction) you can decide what the decimal separator is and simply ignore the other characters, filtering everything except the digits and decimal separator when the field input loses focus. This can help you https://stackoverflow.com/a/48550430/3679111 – Marco Sacchi Sep 22 '21 at 18:32
  • Thank you for your comment, but I still haven't found what I want. – Liza Sep 23 '21 at 07:22

1 Answers1

0

You can cancel the key with the keydown event. Check the can and the prevent the event from happening. I created an example here: https://jsfiddle.net/4ejrfhyp/7/.

Ferry Kranenburg
  • 2,625
  • 1
  • 17
  • 23
  • thank you for the answer. but I didn't get the result I wanted. i want example: 1.000,20 & 0,00 – Liza Sep 22 '21 at 05:48
  • But now you know how to accomplish this yourself. But maybe you're better off using a thirdpary component for this. Check out https://github.com/RobinHerbots/Inputmask, it can do exactly what you want. – Ferry Kranenburg Sep 22 '21 at 16:59
  • Thank you for your comment, but I still haven't found what I want. – Liza Sep 23 '21 at 07:22