jQuery 如何在我输入时格式化输入框文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19470499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to format input box text as I am typing it
提问by annamull654
How do I format the number as I type it in the html input box?
如何在 html 输入框中输入数字时格式化数字?
so for example, I want to type the number 2000, the moment I type the 4th digit, the text (that's currently displayed in the textbox) will be automatically formatted to 2,000 (with a comma).
例如,我想输入数字 2000,当我输入第 4 位数字时,文本(当前显示在文本框中)将自动格式化为 2,000(带逗号)。
//my modified code based on Moob answer below
<input type="text" class="formattedNumberField" onkeyup="myFunc()">
//jQuery
$(".formattedNumberField").on('keyup', function(){
var n = parseInt($(this).val().replace(/\D/g,''),10);
$(this).val(n.toLocaleString());
});
function myFunc(){
// doing something else
}
while this code works perfect as shown in Moob Fiddle, its not working on my end maybe because I have another onkeyup event inside the inputbox???
虽然此代码运行完美,如 Moob Fiddle 所示,但它在我这边不起作用可能是因为我在输入框内有另一个 onkeyup 事件???
回答by Moob
Pure JS (Sans jQuery):
纯 JS(无 jQuery):
var fnf = document.getElementById("formattedNumberField");
fnf.addEventListener('keyup', function(evt){
var n = parseInt(this.value.replace(/\D/g,''),10);
fnf.value = n.toLocaleString();
}, false);
With jQuery:
使用 jQuery:
$("#formattedNumberField").on('keyup', function(){
var n = parseInt($(this).val().replace(/\D/g,''),10);
$(this).val(n.toLocaleString());
//do something else as per updated question
myFunc(); //call another function too
});
To allow decimals:
允许使用小数:
$("#formattedNumberField").on('keyup', function(evt){
if (evt.which != 110 ){//not a fullstop
var n = parseFloat($(this).val().replace(/\,/g,''),10);
$(this).val(n.toLocaleString());
}
});
回答by Patrick Boos
With some code bits of other answers I created the following working example. Code is without jquery, but a little bit longer than some other examples. But it takes care of a lot of the problems that others have.
使用其他答案的一些代码位,我创建了以下工作示例。代码没有 jquery,但比其他一些示例要长一点。但是它解决了其他人遇到的很多问题。
http://jsfiddle.net/kcz4a2ca/10/
http://jsfiddle.net/kcz4a2ca/10/
Code:
代码:
var input = document.getElementById('my_textbox');
var currentValue;
input.addEventListener('input', function(event) {
var cursorPosition = getCaretPosition(input);
var valueBefore = input.value;
var lengthBefore = input.value.length;
var specialCharsBefore = getSpecialCharsOnSides(input.value);
var number = removeThousandSeparators(input.value);
if (input.value == '') {
return;
}
input.value = formatNumber(number.replace(getCommaSeparator(), '.'));
// if deleting the comma, delete it correctly
if (currentValue == input.value && currentValue == valueBefore.substr(0, cursorPosition) + getThousandSeparator() + valueBefore.substr(cursorPosition)) {
input.value = formatNumber(removeThousandSeparators(valueBefore.substr(0, cursorPosition-1) + valueBefore.substr(cursorPosition)));
cursorPosition--;
}
// if entering comma for separation, leave it in there (as well support .000)
var commaSeparator = getCommaSeparator();
if (valueBefore.endsWith(commaSeparator) || valueBefore.endsWith(commaSeparator+'0') || valueBefore.endsWith(commaSeparator+'00') || valueBefore.endsWith(commaSeparator+'000')) {
input.value = input.value + valueBefore.substring(valueBefore.indexOf(commaSeparator));
}
// move cursor correctly if thousand separator got added or removed
var specialCharsAfter = getSpecialCharsOnSides(input.value);
if (specialCharsBefore[0] < specialCharsAfter[0]) {
cursorPosition += specialCharsAfter[0] - specialCharsBefore[0];
} else if (specialCharsBefore[0] > specialCharsAfter[0]) {
cursorPosition -= specialCharsBefore[0] - specialCharsAfter[0];
}
setCaretPosition(input, cursorPosition);
currentValue = input.value;
});
function getSpecialCharsOnSides(x, cursorPosition) {
var specialCharsLeft = x.substring(0, cursorPosition).replace(/[0-9]/g, '').length;
var specialCharsRight = x.substring(cursorPosition).replace(/[0-9]/g, '').length;
return [specialCharsLeft, specialCharsRight]
}
function formatNumber(x) {
return getNumberFormat().format(x);
}
function removeThousandSeparators(x) {
return x.toString().replace(new RegExp(escapeRegExp(getThousandSeparator()), 'g'), "");
}
function getThousandSeparator() {
return getNumberFormat().format('1000').replace(/[0-9]/g, '')[0];
}
function getCommaSeparator() {
return getNumberFormat().format('0.01').replace(/[0-9]/g, '')[0];
}
function getNumberFormat() {
return new Intl.NumberFormat();
}
/* From: http://stackoverflow.com/a/6969486/496992 */
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\^$\|]/g, "\$&");
}
/*
** Returns the caret (cursor) position of the specified text field.
** Return value range is 0-oField.value.length.
** From: http://stackoverflow.com/a/2897229/496992
*/
function getCaretPosition (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;
}
/* From: http://stackoverflow.com/a/512542/496992 */
function setCaretPosition(elem, caretPos) {
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
回答by krasu
Try this plugin it works pretty nice http://robinherbots.github.io/jquery.inputmask/
试试这个插件它工作得很好http://robinherbots.github.io/jquery.inputmask/
回答by moumita kundu
You can use ngx-format-field. It is a directive to format the input value which will appear in the view. It will not manipulate the Input value which will be saved in the backend. See link here!
您可以使用 ngx-format-field。它是用于格式化将出现在视图中的输入值的指令。它不会操作将保存在后端的输入值。在这里查看链接!
Example:
例子:
component.html:
<input type="text" formControlName="currency" [appFormatFields]="CURRENCY"
(change)="onChangeCurrency()">
component.ts
onChangeCurrency() {
this.currency.patchValue(this.currency.value);
}
To see the demo: here!
看演示:在这里!
回答by Lloyd Banks
Based on the example you've given, you can use something like this:
根据您给出的示例,您可以使用以下内容:
$("#my_textbox").keyup(function(){
if($("#my_textbox").val().length == 4){
var my_val = $("#my_textbox").val();
$("#my_textbox").val(Number(my_val).toLocaleString('en'));
}
});
I used jQuery in the above, but it can be done with pure JS also.
我在上面使用了 jQuery,但它也可以用纯 JS 来完成。
Working example here
这里的工作示例