Comma format when entering angular

In jqxwidget http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxnumberinput/index.htm

by default, commas are already set and separated by an underscore.

I want the field to be empty, and as soon as the user begins to enter a comma, it should appear as and when similar to rendering the cell F2.

so when you enter 100 it should display 100 when you enter 10000 it should show 10,000

also i have angular in my application as we use jqxwidget in the market, so any angular way is also good

one plugin that I found does the job, but when the focus is not on typing https://www.npmjs.com/package/angular-numeric-directive

+5
source share
6 answers

Demo

<input value="100000000" id="testInput" /> 

Just apply this .formatInput(numberOfCharactersForSeparator, Separator ); to your entrance

 $(document).ready(function() { $("#testInput").formatInput(3,"," ); }); 

using this plugin i just made: p

 $.fn.formatInput = (function(afterHowManyCharacter,commaType) { if(afterHowManyCharacter && commaType != ".") { var str = $(this).val(); var comma = commaType != undefined ? commaType : "," ; var strMod ; if($(this).val().indexOf(".") == -1) strMod = replaceAll(comma,"",$(this).val()); else { strMod = replaceAll(comma,"",$(this).val()); strMod = strMod.substring(0,strMod.indexOf(".")); } if($(this).val().indexOf(".") != -1) $(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma )+ $(this).val().substring($(this).val().indexOf("."))); else $(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma )); var nowPos = 0; $(this).on("keyup",function(e) { nowPos = doGetCaretPosition($(this)[0]); var codePressed = e.which ; if(" 8 37 38 39 40 46 17".indexOf(" "+codePressed) == -1 && !e.ctrlKey) { if($(this).val().length >afterHowManyCharacter) { strMod ; if($(this).val().indexOf(".") == -1) strMod = replaceAll(comma,"",$(this).val()); else { strMod = replaceAll(comma,"",$(this).val()); strMod = strMod.substring(0,strMod.indexOf(".")); } if($(this).val().indexOf(".") != -1) $(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma )+ $(this).val().substring($(this).val().indexOf("."))); else $(this).val(splitByLength(strMod,afterHowManyCharacter).join( comma )); if((strMod.length-1)%afterHowManyCharacter == 0) { setCursor($(this)[0],nowPos+1); } else { setCursor($(this)[0],nowPos); } } } }); } else if( commaType == ".") { console.log("You can't use . as Separator"); } function splitByLength(str,maxLength) { var reg = new RegExp(".{1,"+maxLength+"}","g"); ; return reverseStringInArray(str.split("").reverse().join("").match(reg).reverse()); } function replaceAll(find, replace, str) { return str.replace(new RegExp(find, 'g'), replace); } function reverseStringInArray(arr) { $.each(arr,function(i,val) { arr[i] = arr[i].split("").reverse().join(""); }); return arr ; } // Author of setCursor is nemisj function setCursor(node,pos) { node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node; if(!node){ return false; }else if(node.createTextRange){ var textRange = node.createTextRange(); textRange.collapse(true); textRange.moveEnd(pos); textRange.moveStart(pos); textRange.select(); return true; }else if(node.setSelectionRange){ node.setSelectionRange(pos,pos); return true; } return false; } // Author of setCursor is bezmax function doGetCaretPosition (oField) { // Initialize var iCaretPos = 0; // IE Support if (document.selection) { // Set focus on the element oField.focus (); // To get cursor position, get empty selection range var oSel = document.selection.createRange (); // Move selection start to 0 position oSel.moveStart ('character', -oField.value.length); // The caret position is selection length iCaretPos = oSel.text.length; } // Firefox support else if (oField.selectionStart || oField.selectionStart == '0') iCaretPos = oField.selectionStart; // Return results return (iCaretPos); } }); 
+3
source

Hey, I solved this earlier by creating a directive that applies a filter to your HTML input. Here is a jsfiddle example

This is a directive. It formats user input and holds the cursor where the user types. My only problem with this is the logic by which the cursor should be pointed.

 fessmodule.directive('format', ['$filter', function ($filter) { return { require: '?ngModel', link: function (scope, elem, attrs, ctrl) { if (!ctrl) return; var parts = attrs.format.split(':'); attrs.foramtType = parts[0]; attrs.pass = parts[1]; ctrl.$formatters.unshift(function (a) { return $filter(attrs.foramtType)(ctrl.$modelValue, attrs.pass) }); ctrl.$parsers.unshift(function (viewValue) { var cursorPointer = elem.context.selectionStart; var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, ''); elem.val($filter(attrs.foramtType)(plainNumber, attrs.pass)); elem.context.setSelectionRange(cursorPointer, cursorPointer); return plainNumber; }); } }; 

And HTML to activate it

 <input type="text" ng-model="test" format="number:2" /> 
+6
source

Angular already provides fairly simple formatting filters like

 html : {{val | number:0}} script: $scope.val = 1234.56789; 

ref:

 https://docs.angularjs.org/api/ng/filter/number https://docs.angularjs.org/api/ng/filter/currency https://scotch.io/tutorials/all-about-the-built-in-angularjs-filters 
+4
source

100 => 100

1000 => 1000

10000 => 10,000

100,000 => 100,000

...

10,000,000 => 10,000,000

10000000.540 => 10 000 000.540

I am using the ng-change event to make this example

  // on-change event $scope.ngchanged = function (val) { $scope.iputval = numberWithCommas(val); }; function numberWithCommas(n) { while (n.toString().indexOf(",") != -1) { n = n.replace(",", ""); } var parts = n.toString().split("."); return parts[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, ",") + (parts[1] ? "." + parts[1] : ""); } 

Use it

 <input type="text" ng-model="iputval" ng-change="ngchanged(iputval)" /> 

Updated adding demo and code at the following link

Full code and demo → here

+1
source
 <html> <script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script> <script> var app = angular.module('app',[]); app.controller('myCtrl',function($scope){ $scope.name = "1232.33"; $scope.changeFormat = function(value){ $scope.name = Number(value).toLocaleString('en'); } }); </script> <body> <div ng-app="app" ng-controller="myCtrl"> <p>Input something in the input box:</p> <p>Number: <input type="text" ng-model="name" placeholder="Enter name here" ng-blur="changeFormat(name)"></p> <h1>Formatted value {{name}}</h1> </div> </body> </html> 
+1
source

Here is the hacker solution. The idea is to keep track of input changes and format the input accordingly.

HTML

 <div ng-controller="so"> <input ng-model="salary"></input> </div> 

Javascript

 app.controller('so', function($scope) { $scope.salary = '12567'; $scope.$watch('salary', function(){ // strip out all the commas and dots var temp = $scope.salary; if (!temp) return; // ignore empty input box var lastChar = temp[temp.length-1]; if (lastChar === ',' || lastChar === '.') // skip it/allow commas return; var a = temp.replace(/,/g,''); //remove all commas //console.log(a); if (isNaN(a)) $scope.salary = temp.substring(0, temp.length-1); // last char was not right else { var n = parseInt(a, 10); // the integer part var f = ''; // decimal part if (a.indexOf('.') >= 0) // decimal present{ if (lastChar === '0') // 0 after decimal point are OK return; f = ('' + parseFloat(a)).substr(a.indexOf('.')); } var formatted_salary = ''; var count = 0; var ns = '' + n; // string of integer part for (var i=ns.length-1; i>=0; i--) { if (count%3===0 && count>0) formatted_salary = ',' + formatted_salary; formatted_salary = ns[i] + formatted_salary; count += 1; } formatted_salary = formatted_salary + (f ? f : ''); $scope.salary = formatted_salary; } }) }) 

Here is the JSFiddle. It gracefully handles things like

  • does not accept any characters other than numbers, and.
  • multiple commas and periods are formatted correctly

PS: - you may need to handle the correct carriage position yourself using a text range. I have not included it here.

+1
source

Source: https://habr.com/ru/post/1233359/


All Articles