这是错误的: jQuery可以在用户输入数字时添加逗号吗?
$('input.number').keypress(function(event){
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/g, '');
$this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
});
Run Code Online (Sandbox Code Playgroud)
空间"1 000 000"我需要"1000000"为"1,000,000"或更好.
请帮忙.谢谢.
小智 11
如果你想拥有类似"1 000 000"的东西,你可以将代码改为这样的东西.
var num = $this.val().replace(/(\s)/g, '');
$this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 "));
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助
$(document).ready(function(){
$('input.number').keyup(function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val().replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
// the following line has been simplified. Revision history contains original.
$this.val(num2);});});
function RemoveRougeChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
Run Code Online (Sandbox Code Playgroud)
根据需要进行编辑 - 同样在jsfiddle中 - jsFiddle
你可以使用Digital Bush的Masked Input Plugin for Jquery.它有许多自定义选项,包括空格,例如:
$("#myInputText").mask("9 999 999",{placeholder:" "})
Run Code Online (Sandbox Code Playgroud)
它似乎已经在不同的浏览器平台上进行了测试,因此它可以帮助您避免一些兼容性测试.
如果您想要更全面的数字掩码支持,可以使用decorplanit.com提供的优秀autoNumeric.他们的网页上有很多例子.
| 归档时间: |
|
| 查看次数: |
48436 次 |
| 最近记录: |