小数位于价格jquery中的自动格式

问题描述 投票:0回答:3

我试图转换小数位qazxsw poi类型qazxsw poi字段之类的

号码从on开始

所以在第一个位置它将是输入字段中的input

比我输入0.00比它应该成为0.00

比我输入1比它应该成为0.01

2所以它应该成为0.12和最后

当我键入0比它应该成为1.20

012.000.010.12

我尝试了一些已经在SO中给出但没有成功的方法。

如果可能,请建议我另一种方法。谢谢。

我试过这样的

1.20
12.00
javascript jquery
3个回答
1
投票

好的,完全不同的解决方案在删除字符时有效:

$(document).on('keyup','.price',function(e){
		var value = $(this).val();
		if(value.length <= 6) {
			if(e.which == 190 || e.which == 46 || e.which == 44 || e.which == 188){
				var amountDots = 0;
				var amountCommas = 0;
				if(value.indexOf(',') > -1){
					amountCommas = value.match(/,/gi).length;
				}
				if(value.indexOf('.') > -1){
					amountDots = value.match(/./gi).length;
				}
				if((amountDots >= 1 && amountCommas >= 1) || amountCommas > 1 || value.length == 1){
					$(this).val(value.substr(0,value.length - 1));
					return false;
				}
				else{
				 	$(this).val(value.substr(0, value.length - 1) + ',');
				}
			}
      
			$(this).val(value/100); //here is the value will insert
      
		} else {
			$(this).val(value.substr(0,value.length - 1))
			return false;
		}
	});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" class="price" />


0
投票

每次新击键时,假设它是一个数字,将它追加到最后,乘以10并显示结果。


0
投票

以下逻辑适用于基本方案。您可能需要单独处理清除文本输入。

$(document).on('keypress','.price',function(e){
    var char = String.fromCharCode(e.which);
    if(isNaN(char)) char = '';
    var value = $(this).val() + char;
    value = value.replace('.','');
    $(this).val((value/100).toFixed(2));
    if(!isNaN(char)) return false;
}).on('keyup','.price',function(e){
    var value = $(this).val();
    value = value.replace('.','');
    $(this).val((value/100).toFixed(2));
});
https://jsfiddle.net/14shzdo5/
© www.soinside.com 2019 - 2024. All rights reserved.