javascript 需要用“点”替换“逗号”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19474977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:42:40  来源:igfitidea点击:

Need to replace "comma" with 'dot'

javascriptjquery

提问by Sergiu Costas

Please help me to adjust an existing script to replace COMMA with DOT. I use a script which limit the inserting character into Text fields. Only 1,2,3,4,5,6,7,8,9,0 and "." and "," are accepted to be inserted. I would like to have two buttons of inserting DOT - key==188 (comma) and key== 190 (dot).

请帮助我调整现有脚本以用 DOT 替换 COMMA。我使用一个脚本来限制插入字符到文本字段中。只有 1、2、3、4、5、6、7、8、9、0 和“。” 和“,”被接受插入。我想要两个插入 DOT 的按钮 - key==188(逗号)和 key==190(点)。

jQuery.fn.ForceNumericOnly =
    function()
    {
        return this.each(function()
        {
            $(this).keydown(function(e)
            {
                var key = e.charCode || e.keyCode || 0;
                return (
                    key == 8 || 
                    key == 9 ||
                    key == 46 ||
                    key == 110 ||
                    key == 188 ||   
                    key == 190 ||
                    (key >= 35 && key <= 40) ||
                    (key >= 48 && key <= 57) ||
                    (key >= 96 && key <= 105));

            });
        });
    };
$("#iMONEY").ForceNumericOnly();

It can be tested HERE

可以在这里测试

回答by Gaurav Bhor

Just use

只需使用

if(e.keyCode == 188){
    e.preventDefault();
    $(this).val($(this).val() + '.');
}

Hereyou go. :)

你。:)

For future references Mini-Tutorial.

供以后参考Mini-Tutorial

回答by Max Koretskyi

var key = e.charCode || e.keyCode || 0;
// 110 is numpad comma code
if (key === 188 && key === 110) {
    e.preventDefault();
    $(this).val($(this).val() + '.');                   
}

回答by Khanh TO

The value of the textbox is updated afterkeypress event is fired. It's not a place to replace comma with dot. Use keyup event instead:

触发 keypress 事件,文本框的值会更新。这不是用点替换逗号的地方。改用 keyup 事件:

jQuery.fn.ForceNumericOnly =
    function()
    {
       this.keyup(function(e)
            {
//                console.log("Change");
                $(this).val($(this).val().replace(/,/g,"."));
            });
    };
$("#iMONEY").ForceNumericOnly();

DEMO

演示

回答by Dawood Awan

You need to use the Replace method

您需要使用 Replace 方法

var someVariable = "1,2,3,4,5,6,7,8,9,0";
$mylabel.text( someVariable.replace(',', '.') );

EDIT:If you are checking from TextBox then do it like this:

编辑:如果您是从 TextBox 进行检查,那么请这样做:

if(Key == 188){
   var someVariable =  $("#TEXTBOXID").val();
    somVariable = someVariable.replace(',', '.');
}