Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

59
Views
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 }
})
8 months ago · Santiago Trujillo
1 answers
Answer question

0

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" />

8 months ago · Santiago Trujillo Report
Answer question
Find remote jobs