Search code examples
ember.jsember-cli

Is it possible to display something other than the input value in a text field?


Right now, I'm trying to have it so that, when a user types in a text field, it'll display the text in a specific format. However, I don't want it to actually change the value of the text field, just change the displayed value.

This is how I'd like for the text to look to the user:

enter image description here

However, it should actually have a value of 500000000, without any of the commas.

Basically, what I need is for it to have a displayed value that's different from the input's actual value.

To do so, I've tried creating a component that extends the Ember.TextField class, like so:

import Ember from "ember";

export default Ember.TextField.extend({
  init: function(){
    this._super();

    var value = this.get('value');
    var money = accounting.formatNumber(value, 0);
    this.set('value', money);
  },
  keyDown: function() {
    var value = this.get('value');
    var unformat = accounting.unformat(value);
    this.set('value', unformat);
  },
  keyUp: function() {
    var value = this.get('value');
    var money = accounting.formatNumber(value, 0);
    this.set('value', money);
  }
});

That formats it well enough, but much of the code relies on grabbing the input's value on the fly. Because of this, is there any way to hide the actual value of the input (so it's available on form submit, and with a few other components that update their values when that text field updates) and display the formatted value? Is there another solution that I haven't found yet?


Solution

  • I recommend using a computed property:

    numberWithCommas: function(key, value, previousValue) {
      // setter
      if (arguments.length > 1) {
        this.set('number', accounting.unformat(value));
      }
    
      // getter
      return accounting.formatNumber(value, 0);
    }.property('number')
    

    Then you can bind your TextField to numberWithCommas and it’ll display with commas, but strip them for storage.