User123
User123

Reputation: 289

How to give Amount field placeholder 00.00 which will change as we enter numbers

I am working on project where I have an amount field to enter my requirement is to display placeholder 00.00 and it should change based on the number user enter.

Ex: If I enter 10 the amount field should be 00.10.

Can any one suggest me how to achieve it.

Upvotes: 0

Views: 490

Answers (3)

nivendha
nivendha

Reputation: 837

var input ="00.00";

//get the key press from input, example:3
var keypressed = 3;
var decimalPresision = input.indexOf('.');
console.log('input',input);
var temp1,temp2;
//remove the first digit and split it at '.'
temp1=input.slice(1).split(".");
console.log('temp1',temp1);
//append the keypressed to the last of string and combine the split string
temp2=temp1[0].concat(temp1[1].concat(parseInt(keypressed)));
console.log('temp2',temp2);
//insert the decimal at the marked precesiion and return the result

result=temp2.slice(0,decimalPresision)+"."+temp2.slice(decimalPresision,temp2.length)
console.log('result',result);

Upvotes: 0

Ced
Ced

Reputation: 17417

Alternatively you can use dir="rtl"

<input placeholder="00.00" id="c" dir="rtl" type="number" step="0.01" max="99.99" min="0">

If you want to have the "." automatically displayed do that in angular.

Upvotes: 0

Ajay Narain Mathur
Ajay Narain Mathur

Reputation: 5466

You can do value of text box * 10 + number entered / 100.

Example snippet:

This is just an example, you need to handle keys other than numbers too.

Update: added placeholder:

angular.module('myApp', [])
  .controller('myCtrl', function($scope) {
    $scope.formatter = function($event) {
      if ($event.which != 8) {
        $event.preventDefault();
        console.log($event.which)
        var temp = $scope.amount || 0;
        console.log($event.key);
        $scope.amount = (($event.key / 100) + temp * 10).toFixed(2);
      } else {
        $scope.amount = ($scope.amount / 10).toFixed(3);
        $scope.amount = $scope.amount == 0.0 ? undefined : $scope.amount;
      }
    }
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
  <input type="text" placeholder="00.00" ng-keypress="formatter($event)" ng-model="amount" />
</div>

Upvotes: 1

Related Questions