Skip to content
Advertisement

Ember input type number to allow only 2 digits after Decimal

I am working on an Ember application, an input type number as below

 ${{input type="number" id=p.ViolationTypeId 
          value=p.PenaltyAssessed maxlength="5" 
          scale="0.01" pattern="^d+(.d{0,2})?$" 
          key-down=(action 'allowOnly2Decimals') 
          focusOut=(action 'saveTotalPenalty' p model.id p.PenaltyAssessed)}}

Then I have a following JavaScript Code written to limit the entry of digits after decimal, this function is called in Key-Down event.

    allowOnly2Decimals: function (e1, event) {
            var boxId = '#' + event.path[0].id;

            //if ((event.keyCode == 190) || (event.keyCode == 110)) {
            //    this.decimalPressed = true;
            //}

            var t = e1.toString().split('.');

            if (t[1] != null) {
                if (t[1].length == 2) {
                    this.limitDecimal = e1;
                    $(boxId).val(e1);
                }

                if (t[1].length >= 2) {
                    e1 = this.limitDecimal;
                    $(boxId).val(e1);

                    return false;
                }
            }
        }
    }

Its working but what it is doing it, it allowing 3 digits after decimal but when I am posting its value on the Service, that is taking correctly 2 digits after decimal but what it is showing in the Textbox is 3 digits after decimal. And another request if possible is, can I do the same without using id attribute on the Textbox.

Any help please, thanks in advance.

Advertisement

Answer

To answer your first question, the reason it is allowing 3 values is because you are using the keydown event. The keydown event is fired before the input is updated so you’re always 1 character behind the actual value. I would recommend instead of using keydown, to use the change event. If you really have to mangle the user’s inputs as they type, use the keyup event instead.

To answer your second question, you can access the input via event.target i.e. $(event.target).val(e1);

Finally your code is making some assumptions about the user’s input, what happens if they paste in a value that is longer than 2 characters after the decimal?

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement