2

I called a class called test for my textbox. When I entered the first value for e.g. the first value as 4., then suddenly the output coming as 4.00. I just want to restrict entry only for two decimal places.

$(".test").keyup(function (event) {
    debugger;
    this.value = parseFloat(this.value).toFixed(2);
});
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
user2156088
  • 2,350
  • 5
  • 20
  • 24

5 Answers5

2

This small change to your code may suffice:

  this.value = this.value.replace (/(\.\d\d)\d+|([\d.]*)[^\d.]/, '$1$2');

Essentially replace the decimal point followed by any number of digits by a decimal point and the first two digits only. Or if a non digit is entered removes it.

HBP
  • 15,685
  • 6
  • 28
  • 34
0

What about something like this:

$(".test").keyup(function (event) {
if ((pointPos = this.value.indexOf('.')) >= 0)
    $(this).attr("maxLength", pointPos+3);
else
    $(this).removeAttr("maxLength");
});

Here is a working fiddle.

Aioros
  • 4,373
  • 1
  • 18
  • 21
  • I liked ur work. I got problem when i reached 2 decimals `23.45` and again i cant insert number before decimal like `234.45. its even after deleting number before decimal – Lakshmana Kumar May 21 '13 at 09:46
  • @Aioros:Hai the code is working .But one issue is there the delete button is not working after entering the number.Do you know the reason? – user2156088 May 21 '13 at 10:08
0

you can use the maxLength attribute for that, try

 $(".test").keyup(function (event) {
        var last = $(this).val()[$(this).val().length - 1];
        if (last == '.') {
            $(".test").attr("maxlength", $(this).val().length+2);
         }
    });
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

You shouldn't worry about what the user has in the input until they submit the form. You really don't care what's in there before then. However, if you want to warn about invalid input, you can put a message on the screen if you detect non–conforming input, e.g.

<script>

function validate(element) {
  var re = /^\s*\d*\.?\d{0,2}\s*$/;
  var errMsg = "Number must have a maximum of 2 decimal places";
  var errNode = document.getElementById(element.name + '-error')
  if (errNode) {
    errNode.innerHTML = re.test(element.value)? '' : errMsg;
  }
}

</script>    

You should probably also put a listener on the change handler too to account for values that get there by other means.

RobG
  • 142,382
  • 31
  • 172
  • 209
0
$(document).on("keyup", ".ctc", function () 
 {

    if (!this.value.match(/^\s*\d*\.?\d{0,2}\s*$/) && this.value != "") {
        this.value = "";
        this.focus();
        alert("Please Enter only alphabets in text");
    }
});
kleopatra
  • 51,061
  • 28
  • 99
  • 211
vino20
  • 429
  • 4
  • 13