最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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

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 ing 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);
});
Share Improve this question edited May 21, 2013 at 9:23 Felix Kling 817k181 gold badges1.1k silver badges1.2k bronze badges asked May 21, 2013 at 9:21 user2156088user2156088 2,4206 gold badges22 silver badges24 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 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.

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.

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

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.

$(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");
    }
});
发布评论

评论列表(0)

  1. 暂无评论