我想在输入数字后删除文字并添加小数
我有多个input type="text"
在按键上我在INR(印度卢比)标准中添加逗号但是当我输入三个以上的数字时,整个值都被移除并且' 0' 0被添加。我的代码也不允许使用十进制.00数字。我做错了什么?
HTML:
<input name="txtMSExMarCardFee" type="number" id="txtMSExMarCardFee" class="Stylednumber">
<input name="txtMSExMarCardFee1" type="number" id="txtMSExMarCardFee1" class="Stylednumber">
<input name="txtMSExMarCardFee2" type="number" id="txtMSExMarCardFee2" class="Stylednumber">
JS:
$('input.Stylednumber').keyup(function(){
var x=$(this).val();
x=x.toString();
var afterPoint = '';
if(x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'),x.length);
x = Math.floor(x);
x=x.toString();
var lastThree = x.substring(x.length-3);
var otherNumbers = x.substring(0,x.length-3);
if(otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
$(this).val(res );
});
答案 0 :(得分:1)
这要求您在将输入传递给正则表达式
之前清理输入
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
$('input.Stylednumber').keyup(function() {
var input = $(this).val().replaceAll(',', '');
if (input.length < 1)
$(this).val('0.00');
else {
var val = parseFloat(input);
var formatted = inrFormat(input);
if (formatted.indexOf('.') > 0) {
var split = formatted.split('.');
formatted = split[0] + '.' + split[1].substring(0, 2);
}
$(this).val(formatted);
}
});
function inrFormat(val) {
var x = val;
x = x.toString();
var afterPoint = '';
if (x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'), x.length);
x = Math.floor(x);
x = x.toString();
var lastThree = x.substring(x.length - 3);
var otherNumbers = x.substring(0, x.length - 3);
if (otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
return res;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="txtMSExMarCardFee" type="text" id="txtMSExMarCardFee" class="Stylednumber">
<input name="txtMSExMarCardFee1" type="number" id="txtMSExMarCardFee1" class="Stylednumber">
<input name="txtMSExMarCardFee2" type="number" id="txtMSExMarCardFee2" class="Stylednumber">
答案 1 :(得分:0)
尝试使用:
$('input.Stylednumber').keyup(function(){
var t = $(this), v = t.val();
if(!v.match(/\.\d{2}$/)){
v += '.00';
}
v = parseFloat(v.replace(/,/g, ''));
if(!v){ // was not a number
t.val('0.00');
return false;
}
v = v.toFixed(2);
if(v.length > 6){
t.val(v.slice(0, -6).replace(/(/d{3})/, '$1,')+v.slice(-6));
}
else{
t.val(v);
}
});