0

So I'm new to Ember and have been doing some digging around for the a while looking for the answer to this.

What I have is a field and I want to restrict the use of whitespace (basically if the user hits the spacebar, I don't want it to do anything).

The issue, is that I can still hit the spacebar and add multiple spaces, and it's not until I hit another character that the value loses all the whitespace (To help this description, instead of swapping spaces, I'm going to swap the letter 'a').

So far I have an observer and a function (in my component js file):

emailChanged: Ember.observer('email', function() {
  // console.log('email changed');
  Ember.run.once(this, 'formatEmail');
}),

formatEmail() {
   // console.log('email', this.get('email')); 
   this.set('email', this.get('email').replace(/a/g, ''));
  // console.log('should be', this.get('email'));
},

So what is happening is that (when I use the console logs).

If I type a 'b' character in the console I get, email changed, then email b, then should be b.

When I type 'a', in the console I get email changed then email ba, then formatEmail() actually runs and changes the email, so then I get should be b, email b, should be b.

But it's still displaying 'ba'.

Hard to explain this, but basically, it looks like set is working, except that it's not changing what is displayed on the screen.

Ember-twiddle

Brett East
  • 4,022
  • 2
  • 20
  • 31

1 Answers1

1

Working demo on Ember Twiddle.

I've changed a bit your input to handle email changes via an action instead of two-way-binding:

<input id='email' value={{email}} oninput={{action 'emailInput'}} />

And then in your component, I've added an action:

actions: {
    emailInput(event) {
        const $input = $(event.target);
        const value = $input.val();
        const withoutSpaces = value.replace(/\s+/g, '');

        this.set('email', withoutSpaces);
        $input.val(withoutSpaces);
    }
}

The key function here is using .val() to set input value:

$input.val(withoutSpaces);

Without it, the value in the input would not change.

Daniel Kmak
  • 18,164
  • 7
  • 66
  • 89
  • 1
    Works great. I'm also mixing it with https://stackoverflow.com/questions/14508707/updating-an-inputs-value-without-losing-cursor-position, so that the cursor doesn't change position. – Brett East Jul 20 '17 at 21:05
  • Good stuff! Will remember if I encounter similar issue! Thanks! – Daniel Kmak Jul 20 '17 at 21:10