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)
source to share
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 eventkeydown
orkeypress
. -
Change
value.replace(",", ".")
tovalue + "."
(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.
source to share