Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only allow 1 comma and 2 decimal after it

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 }
})
like image 337
Mr always wrong Avatar asked Oct 17 '22 16:10

Mr always wrong


1 Answers

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" />
like image 116
Sami Avatar answered Oct 21 '22 04:10

Sami