You must Sign In to post a response.
  • Category: JavaScript

    How to write java script for accept only decimal no which is not > 20?


    You want to write a Javascript for accepting number with specific condition? Read this thread to learn how to accept only decimal numbers.



    How to write java script for accept only decimal no which is not > 20 and before decimal point accept 2 digit only but not > 20 and after decimal point accept only 0 and 5
  • #749140
    I didn't get your requirement after decimal point so i gave you some snippet for that and modify it according to your need.

    function checkDec(el) {
    var ex = /^[0-9]+\.?[0-9]*$/;
    if (ex.test(el.value) == false) {
    el.value = el.value.substring(0, el.value.length - 1);
    }

    if (el.value.length == 2) {
    if (txtValue.value > 20) {
    alert("Value must be less than 20.");
    } else {
    txtValue.value = el.value + ".";
    }
    }

    if (el.value.split(".").length == 2) {
    if(el.value.split(".")[1].length>2){
    //Put your logic for after decimal points
    }
    } else {
    //Put your logic for after decimal points
    }
    }

    <input type="text" id="txtValue" onkeyup="checkDec(this);" />

    Regards,
    Nirav Prabtani (Senior Web Developer)
    Email : niravjprabtani@gmail.com
    blog : niravprabtani.blogspot.in

  • #749145
    You can achieve you task with the help of following regular expression in javascript,


    var val = document.getElementById("txtInput").value;
    var re = "^\d{1,5}(?:\.\d{1,2})?$";
    if (! re.test(val))
    {
    //Regular expression failed

    }

    hope it helps

    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]

  • #749149
    Hi,
    I am bit confused with your post. Do you want to block user entering the numeric value greater than 20?

    Use below regular expression to validate 2 decimal places without % symbol,

    ^[\d,]+(\.\d{1,2})?$



    Use below regular expression to validate 5 decimal places with an optional % symbol.

    ^\d{1,9}(\.\d{1,2})?%?$


    Let me know if any of the above code doesn't works for you.


    Regards,
    Asheej T K

  • #749154
    [Response removed by Admin. Read forum policies.]


  • Sign In to post your comments