Mowzer Mowzer - 1 month ago 12
Javascript Question

Polymer 1.x: How to format a number while typing it into paper-input?

TL;DR: I want my numbers to look like 1,500 (not 1500) when entering it in an

<input
(actually
<paper-input
or even
<iron-input
?) form field. Similar to this example except using Polymer only and not AngularJS.

I want to format a number in
paper-input
(using, say, Numeral.js) while it's being entered by the user. I don't really know where to begin or what to try. I want to access the numeric value in the JS, but I want the user to be able to see the nicely formatted (string) version while entering it.

Is this even possible? Or perhaps I might need a separate display field? But then that would defeat the purpose of the
paper-elements
from a UX standpoint? Any help?

Also, note per the second comment on this SO question:


Worth noting that
Number.prototype.toLocaleString
still does not work in Safari, in 2016. Instead of actually formatting the number, it just returns it, no error thrown. Having the biggest facepalm today as a result of that... #goodworkApple – aendrew


Here is the jsbin. ... http://jsbin.com/wosoxohixa/1/edit?html,output

http://jsbin.com/wosoxohixa/1/edit?html,output

<!doctype html>
<head>
<meta charset="utf-8">
<base href="https://polygit.org/components/">
<script src="webcomponentsjs/webcomponents-lite.min.js"></script>
<link href="polymer/polymer.html" rel="import">
<link href="paper-input/paper-input.html" rel="import">
<script src="//cdnjs.cloudflare.com/ajax/libs/numeral.js/1.4.5/numeral.min.js"></script>
</head>
<body>

<dom-module id="x-element">

<template>
<style></style>

<paper-input value="{{num}}"></paper-input>

</template>

<script>
(function(){
Polymer({
is: "x-element",
properties: {
num: {
type: Number,
value: function() {
return numeral(1500).format('0,0');
},
},
},
});
})();
</script>

</dom-module>

<x-element></x-element>

</body>

Answer

I do something similar with a datepicker based around paper input. Put an observer on the num property, and it will get called as every new character arrives.

You also need to be careful with validation as you may end up trying to validate 1,0 if that is the way the user has typed it in. (assuming he may type with or without your formatiing