3

我在 AppJs 中做了一个计算应用程序。

基本上它是一堆:

 <input type=number> 

字段。

为了使其更加用户友好,我认为我应该用点替换所有逗号,以便 javascript 可以使用实际值来计算。

我已经尝试使用以下代码来执行此操作:

$("input[type=number]").keyup(function(e){
        var key = e.which ? e.which : event.keyCode;
        if(key == 110 || key == 188){
          e.preventDefault();
          var value = $(this).val();         
          $(this).val(value.replace(",","."));
        }   
});

在 explorer 9 中,这按预期工作:见 fiddle

但由于 App.js 使用铬,我想这是铬中发生的事情。我该如何解决这个问题?

这就是我的应用程序中发生的情况:当您输入一个包含逗号字符的数字时。逗号字符向右移动,当输入框失去焦点时,逗号被删除(可能是因为逗号字符在type=number中是不允许的)

4

3 回答 3

6

When you get the value of an <input type=number> but it isn't valid, then a blank string is returned. You could check this by doing this:

$("input[type=number]").keyup(function(e){
        var key = e.which ? e.which : event.keyCode;
        if(key == 110 || key == 188){
          e.preventDefault();
          var value = $(this).val(); 
          console.log(value === "");        
          $(this).val(value.replace(",","."));
        }   
});

It will print true every time. Therefore, you need to

  1. Since, on the keyup event, the input has already changed, you must change it to a keydown or keypress event.

  2. Change value.replace(",", ".") to value + "." (since there will be no ",").

  3. Actually, you need to insert it where the cursor is. I'll update that when I have time.

Finished code:

$("input[type=number]").keydown(function (e) {
    var key = e.which ? e.which : event.keyCode;
    if (key == 110 || key == 188) {
        e.preventDefault();
        var value = $(this).val();
        console.log(value);
        $(this).val(value + ".");
    }
});

A better idea might be to make it <input type=text> and validate manually if you really need this feature.

于 2014-08-17T20:10:05.457 回答
1

最好不要弄乱输入字段中的实际数据,而是在读取之前在内部重新格式化,通过像这样的 getter 访问值:

var getInputNumber = function(inputid) {
    return $(inputid).val().replace(",", ".");
};
于 2014-08-17T19:39:23.323 回答
0
        $("input").keydown(function (e) {
            var key = e.which ? e.which : event.keyCode;
            if (key == 110 || key == 188) {
                var value = $(this).val();
                if (!isNaN(value)) {
                    e.preventDefault();
                    $(this).val(value + ".");
                }
            }
        });
于 2015-06-10T10:57:14.207 回答