user2156088
user2156088

Reputation: 2420

Allow only 2 decimal points entry to a textbox using javascript or jquery?

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);
});

Upvotes: 2

Views: 14190

Answers (5)

vino20
vino20

Reputation: 429

$(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");
    }
});

Upvotes: 0

HBP
HBP

Reputation: 16063

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.

Upvotes: 2

RobG
RobG

Reputation: 147523

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.

Upvotes: 0

Anoop Joshi P
Anoop Joshi P

Reputation: 25537

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);
         }
    });

Upvotes: 0

Aioros
Aioros

Reputation: 4383

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.

Upvotes: 0

Related Questions