mafortis
mafortis

Reputation: 7128

vuejs add comma to numbers while typing

I want to add separator in my numbers while i'm typing but it doesn't work.

Code

<el-input-number v-model="form.qty" style="width: 100%;" id="test" placeholder="Quantity" controls-position="right" v-on:keyup="handleChange" :min="1"></el-input-number>

methods: {
    handleChange: function(value) {
        let vm = this;
        console.log(value);
        const result = value.toString().replace(/\D/g, "")
            .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            Vue.nextTick()
            .then(function () {
                vm.form.qty = result
            });
    },
}

one

issue

Currently when i'm typing numbers no comma adds to input field but when i'm sending my values to back-end it sends it with commas.

What I need

What I need is the exact opposite behavior than I explained above,

  1. show numbers with commas in view
  2. send it to back-end without commas

Any idea?

Upvotes: 1

Views: 6641

Answers (2)

Jason Smith
Jason Smith

Reputation: 1209

I don't use ElementUI, so I can't confirm that el-input-number will accept a formatted string value. It's possible that that component internally strips all non-numeric characters from the value prop. However, the solution below works on standard text inputs.

In order to display something different than you store, you need to split the v-model directive back into its original parts. v-model is just a shortcut for binding value and @input in a single directive. You should store the un-formatted number in your form.qty field, but supply the el-input-number component with the formatted number via a computed property, like this:

<template>
  <!-- INSTEAD OF v-model, use :value and @input -->
  <el-input-number :value="formattedQty" @input="handleQtyInput" />
</template>

<script>
export default {
  data () {
    return {
      form: {
        qty: "0",
      }
    }
  },

  computed: {
    formattedQty () {
      //Add the commas back to the string
      let qty = this.form.qty + ""
      return qty.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
    }
  },

  methods: {
    handleQtyInput (newValue) {
      //Make sure the stored qty is not formatted
      this.form.qty = newValue.toString().replace(/\D/g, "")
    }
  }
}
</script>

Upvotes: 1

Pratik Patel
Pratik Patel

Reputation: 6978

I think this is just reactivity problem instead of using = use $set.

handleChange(value) {
        console.log(value);
        let vm = this;
        let res = value.toString().replace(/\D/g, "")
            .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
        console.log(res)
        this.$set(this.form,'num',res);

      }

Fiddle - https://jsfiddle.net/PratikPatel227/tLx3z96a/28/

while sending data use - this.form.num.replace(/,/g, '')

Upvotes: 1

Related Questions