2

Restricting user to enter values upto two decimal i.e. 10.56 only.

<input class="number" type="text" value="" />
<input type="text" value="44" />
$('.number').on('keypress',function (event) {
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
    var input = $(this).val();
    if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
        event.preventDefault();
    }
});

The fiddle works. But if a user press delte/tab/backspace, nothing happens.

How to allow user to edit/delete input value or move to next input box using tab button ?

Answer Reference : Link

Community
  • 1
  • 1
Slimshadddyyy
  • 4,085
  • 5
  • 59
  • 121

1 Answers1

2

You can escape the related keyboards keys. See the Javascript Char Codes, to know the key escaped.

See live demo :

$('.number').on('keypress',function (event) {

  // Add this condition to escape arrow/tab/delete/... and many others keys
  if(event.which <= 46) {
    return true;
  }

  if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
    event.preventDefault();
  }
  var input = $(this).val();
  if ((input.indexOf('.') != -1) && (input.substring(input.indexOf('.')).length > 2)) {
    event.preventDefault();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="number" type="text" value="" />

<input type="text" value="44" />

Update :

Add in your fiddle an if confition :

var acceptedKeys = [9, 37, 39, 46, 8];
if(acceptedKeys.indexOf(charCode) > -1) {
    return true;
} 

With this code you accept this keys :

  • backspace
  • delete
  • left arrow
  • right arrow
  • tab

http://jsfiddle.net/e0orb0qq/29/

R3tep
  • 12,512
  • 10
  • 48
  • 75
  • R3tep: How can we make it work with this fiddle - http://jsfiddle.net/e0orb0qq/22/ using only JS ? – Slimshadddyyy May 13 '15 at 06:54
  • R3tep: Thanks for the fiddle, but now it allows to enter more than two decimal values which should not – Slimshadddyyy May 13 '15 at 08:40
  • @Slimshadddyyy http://jsfiddle.net/e0orb0qq/25/ This is my last fiddle. I am not here to develop for you! – R3tep May 13 '15 at 08:45
  • Agree that you are not here to develop for me, but in the fiddle if you delete a value say `10.55`, using delete button, and try to change it to say `8.55`, it does not allow i.e. value before decimal can not be changed – Slimshadddyyy May 13 '15 at 09:11