If your goal is to stop not only him being typed, but that it is used as value anyway (eg: copy and paste) I suggest listening to the property input
and adjust the value according to its rule (in this case, delete the commas):
$('input').on("input", function(e) {
$(this).val($(this).val().replace(/,/g, ""));
});
Example in jsFiddle. In some older browsers, you may also need to listen by propertychange
(but I believe that input
is widely supported).
This way, it doesn’t matter if the comma was typed on the "normal" keyboard, the number pad, Ctrl+C Ctrl+V or even Right-click and "paste". The value will be maintained without the comma in all cases, and no visual Glitch will occur.
P.S. See also that question I did some time ago at SOEN, for more details.
This solution is better than mine, I did not know this event! It is the reference: https://developer.mozilla.org/en-US/docs/Web/Reference/Events/input
– bfavaretto
Great solution. I will use it
– Joao Paulo
This one has the annoying problem of not keeping the cursor in the right place. Some way to do this?
– Guilherme Bernal
@Guilhermebernal Cara, I have the same problem! I’ll even take a look at the plugin indicated by utluiz, because at the moment I do not know any solution. I’ve been reading methods to manipulate the cursor in the browser, but I gave up because of the complexity...
– mgibsonbr