Home > Enterprise >  value is lost while changing input type on focus
value is lost while changing input type on focus

Time:08-18

The scenario I want to meet is, initially an amount is shown as a value and that time I need to show value with currency and comma if applicable, however, while sending the value when user changes it then it should be sent as a number(without currency sign and comma). For this case what I tried is when user focuses on input field that means user wants to update the value so I change input type from 'text' to 'number' but doing that I loose value. How can I still persist that value?

Here is how I have done

<input
  name="text"
  :type="type"
  v-model="amount"
  
  @focus="handleAmountFocus($event)"
  required
  placeholder="Set amount"
  style="height: 30px"
  min="0"
  @keyup="handleInput($event)"
/>

handleAmountFocus(e) {
  if (this.type === 'number') this.type = 'text'
  this.type = 'number'
},
handleInput(e) {
  if (e.key === '-') {
    e.target.value = 0;
  } else {
    return e.target.value;
  }
},
save(field) {
  debugger
  var cleanedVal = this[field];
  this.actual_amount = cleanedVal;
  var updated_amount = new Intl.NumberFormat(undefined).format(cleanedVal);
  if (updated_amount == '0' || updated_amount == 'NaN') {
    this.amount = 0;
  } else {
    this.amount = '$'   updated_amount;
  }
  if (this[field]) {
    const formData = {
      amount: cleanedVal || 0,
    };
    // send this to server
  }
}

Could anyone please help me? I would appreciate any kind of help.

enter image description here

Now when user selects or touches that input field, the value "10000" gets lost which is not what I want. I want that 10000 still be there when user focuses on input and be able to change the value

enter image description here

CodePudding user response:

Try to change the type and the value inside the @focus and @blur event handlers as shown in the following example

var demo = new Vue({
  el: '#demo',
  data: {
    amount: 0,
    type: 'text'
  },
  methods: {
    onFocus() {
      this.amount =  String(this.amount).replace('$', '') //  casts string to number  '4' gives 4
      this.type = "number";

    },
    onBlur() {
      this.type = "text";
      this.amount = String('$'   this.amount)

    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <input v-model="amount" @focus="onFocus" @blur="onBlur" :type="type"/>
</div>

CodePudding user response:

Try using input mask, there are plenty of masks that meets your requirements. Thanks

  • Related