在我输入时如何格式化输入框文本 [英] how to format input box text as I am typing it
本文介绍了在我输入时如何格式化输入框文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在html输入框中输入数字格式化数字?
How do I format the number as I type it in the html input box?
所以例如,我想输入数字2000,我输入的那一刻第四位数字,文本(当前显示在文本框中)将自动格式化为2,000(带逗号)。
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).
//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
}
虽然这个代码工作得很完美,如Moob Fiddle所示,但它不能在我的工作结束可能因为我在输入框中有另一个onkeyup事件???
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???
推荐答案
纯JS(Sans 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);
使用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
});
允许小数:
$("#formattedNumberField").on('keyup', function(evt){
if (evt.which != 110 ){//not a fullstop
var n = parseFloat($(this).val().replace(/\,/g,''),10);
$(this).val(n.toLocaleString());
}
});
这篇关于在我输入时如何格式化输入框文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文