键盘事件中的javascript数字格式 [英] javascript number formatting on keyup event

查看:113
本文介绍了键盘事件中的javascript数字格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在键盘输入事件中在输入字段中设置数字格式,但是我在浏览器的控制台上一直收到警告 无法解析指定的值"5,545",或超出范围. 我在输入字段中输入的值将被清除.请问如何解决该问题?
下面是处理数字格式的jquery代码段:

I am trying to format number in an input field on keyup event but I kept getting a warning on the console of my browser The specified value "5,545" cannot be parsed, or is out of range. and the value I have entered in the input field cleans up. Please what can be done to solve the problem?
Below is the jquery code snippet that handles the number formatting:

$('input[type="number"]').keyup(function(event) {
        // skip for arrow keys
        if(event.which >= 37 && event.which <= 40){
            event.preventDefault();
        }
        $(this).val(function(index, value) {
            return value
            .replace(/\D/g, "")
            .replace(/([0-9])([0-9]{2})$/, '$1.$2')  
            .replace(/\B(?=(\d{3})+(?!\d)\.?)/g, ",");
        });
    });


我在浏览器控制台中遇到的错误或警告是:

,显示此警告后,输入字段中的值将清除.请问哪里有问题,该怎么办?


Error or warning I get in the browser console is:

and the value in my input field cleans up after displaying this warning. Please what is wrong and what can be done?

推荐答案

导致错误的原因是,,因为5,289尝试将,更改为.

What causes the error is the , since 5,289 try changing the , to a .

EX: '5,289' => '5.289'

这篇关于键盘事件中的javascript数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆