我想创建一个javascript代码来格式化我的输入数字。例如,当用户输入:100000时,它会自动转换为100,000,如果用户输入1000.22,则会产生1,000.22。我创建了这样的代码:
$(document).ready(function(){
$('input.angka').on("keyup click", 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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" class="angka form-control" name="hargak" onkeyup="tots();" />
所以我的所有输入文本框都会转换为'angka'类。如果我输入没有小数(10000,20000等),它的工作原理。但是,当我使用十进制,这些代码出错(1000.22将导致1,000,。22)任何人都可以修复此代码?
答案 0 :(得分:1)
一种可能性...... 您还应该接受左右箭头导航......
$(document).ready(function(){
$('input.angka').on("keyup click", function(event){
// skip for arrow keys
if(event.which >= 37 && event.which <= 40){
event.preventDefault();
}
var $this = $(this);
var num = $this.val();
var decs = num.split(".");
num = decs[0];
num = num.replace(/,/gi, "").split("").reverse().join("");
var num2 = RemoveRogueChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));
if(decs.length > 1) {
num2 += '.' + decs[1];
}
$this.val(num2);
});
});
function RemoveRogueChar(convertString){
if(convertString.substring(0,1) == ","){
return convertString.substring(1, convertString.length)
}
return convertString;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="text" class="angka form-control" name="hargak" onkeyup="tots();" />