I have a code that allows me couple things like only digit backspace. How can I change the regex that it will allow to press "enter" and allows only 1 comma and after the comma max 2 numbers?
$("[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 }
})
Here's a bit verbose version. This accepts arrow keys, tab, enter, 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" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With