Allow only 1 comma and 2 decimal places after it

Hi guys, I have a code that allows me a couple of things, as soon as the backspace is, how can I change the regular expression so that it can press enter and only allow 1 comma and max 2 numbers after the comma?

$("[name=price]").keydown(function(e){ if(e.keyCode == 110 || e.keyCode == 190) { e.preventDefault(); $(this).val($(this).val() + ','); } if (/\d|,+|[b]+|-+/i.test(e.key) ){ }else{return false } }) 
+5
source share
1 answer

Here is a laconic version. It accepts arrow keys, tabs, input, modifiers, etc.

 $("[name=price]").keydown(function(e) { if (e.keyCode == 110 || e.keyCode == 190 || e.keyCode == 188) { if ($(this).val().indexOf(',') > -1) { return false; } else { e.preventDefault(); $(this).val($(this).val() + ','); } } else if (e.keyCode < 47) { } else if (/\d|,+|-+/i.test(e.key)) { if ($(this).val().indexOf(',') > -1) { if ($(this).val().substr($(this).val().indexOf(',') + 1).length >= 2) { return false; } } } else { return false } }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input name="price" /> <input name="price" /> <input name="price" /> 
+3
source

Source: https://habr.com/ru/post/1265127/


All Articles