In many cases when we develop web pages for business purposes, we may need to limit the text field numeric only(age,phone numbers etc). Same way, customers need the currency to be entered separated by comma,instead of seeing it as plain numbers. Here I am adding the code snippets to make the SAPUI5 text field to cater both the cases.
var textbox = new sap.ui.commons.TextField("data",{
textDirection : sap.ui.core.TextDirection.RTL
});
For this, we need to register browser event "keypress" for the textbox, so that the corresponding event handler would handle the pressed key, and check if it is a number or not.
textbox.attachBrowserEvent("keypress",function(e){
var key_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8];
if (!($.inArray(e.which, key_codes) >= 0)) {
e.preventDefault();
}
});
where , [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8] is the array of ASCII values ranging from 0 to 9. It makes sure that the hit key is in this range.
Now the text box is numbers only.
All we need is to define a JavaScript function to put the comma between the digits properly, and handle the decimal places. Here, for this example, I consider INR so that the comma separation will be 3,2,2.. pattern and is having 2 decimal places.
Instead of keypress , we will be using keyup event to capture the data.
textbox.attachBrowserEvent("keyup",function(e){
var Number1 = e.srcElement.value; // source element pointer with data
var CommaSeperaterList = '3,2,2,2,2,2,2,2,2';
var Number = Number1.replace(/\,/g, '');
var myArray = CommaSeperaterList.split(',');
var newNum = "";
var newNum2 = "";
var end;
var count = 0;
if (Number.indexOf('.') != -1) {
places = Number.length - Number.indexOf('.') - 1;
if (places >= 3) {
num = parseFloat(Number);
Number = num.toFixed(2);
}
var a = Number.split(".");
Number = a[0];
end = '.' + a[1];
}
else { var end = ""; }
var q = 0;
for (var k = Number.length - 1; k >= 0; k--) {
ar = myArray[q];
var oneChar = Number.charAt(k);
if (count == ar) {
newNum += ",";
newNum += oneChar;
count = 1;
q++;
continue;
}
else {
newNum += oneChar;
count++;
}
}
for (var k = newNum.length - 1; k >= 0; k--) {
var oneChar = newNum.charAt(k);
newNum2 += oneChar;
}
e.srcElement.value = newNum2 + end;
});
where, '3,2,2,2,2,2,2,2,2' is being the comma places. Based on the currency type, we can change it and adapt new comma separation system.
Number = num.toFixed(2); statement fixes the decimal places to 2.
Regards,
Sreehari.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
User | Count |
---|---|
9 | |
7 | |
4 | |
4 | |
3 | |
3 | |
3 | |
3 | |
3 | |
3 |