Replacing a Char with a comma

I made an app for calculating in AppJs.

It's basically a bunch:

 <input type=number> 

      

fields.

To make it more user friendly, I thought I should replace all commas with periods so that javascript can use the actual values ​​to calculate.

I tried to do it with the following line of code:

$("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(",","."));
        }   
});

      

In explorer 9, this works as expected: see fiddle

But since App.js is using chrome, I think this is something that is happening in chrome. How can I get around this?

This is what happens in my application: When you enter a number that contains a comma char. The char comma is moved to the right, and when the input field loses focus, the comma is removed (possibly since char comma is not allowed in type = number)

+3


source to share


3 answers


When you receive a value <input type=number>

that is invalid, an empty string is returned. You can check this by following these steps:

$("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

  • Since the keyup

    input has already changed in the event , you must change it to event keydown

    or keypress

    .

  • Change value.replace(",", ".")

    to value + "."

    (since there won't be ","

    ).

  • Actually, you need to paste it where the cursor is. I will update this 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 do it <input type=text>

and manually test it if you really need this feature.

+6


source


It's probably best not to tamper with the actual data in the input field, but format first before reading, accessing the value through a getter like this:



var getInputNumber = function(inputid) {
    return $(inputid).val().replace(",", ".");
};

      

+1


source


        $("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 + ".");
                }
            }
        });

      

0


source







All Articles