Click here to Skip to main content
15,897,519 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I wrote a java-script function like below: to Only allow gridview textbox to take decimal number between 0-5. But the problem is it takes more than only one single point in decimal numbers and it also does not take anything greater than 5 even after decimal points. so i m not been able to write 3.8/4.8/2.6 type of value in textbox
JavaScript
<script type="text/javascript">
    var specialKeys = new Array();
    specialKeys.push(8); //Backspace
    $(function () {
        $(".numeric").bind("keypress", function (e) {
            var keyCode = e.which ? e.which : e.keyCode
            var ret = ( keyCode== 46 || (keyCode >= 48 && keyCode <= 53 ) || specialKeys.indexOf(keyCode) != -1);
            if (ret) {
                $(this).next().remove();
            }

            else {
                if (!$(this).next().hasClass("error")) {
                    $(this).after("<span class = 'error'><br />* Input digits (1-5)</span>");
                }
            }
            return ret;
        });

            $(".numeric").bind("paste", function (e) {
                return false;
            });
            $(".numeric").bind("drop", function (e) {
                return false;
            });
        });

</script>


can anyone give me any suggestion to solve that problem?
Posted

1 solution

Try with below code:
JavaScript
$(".numeric").bind("keypress", function (e) {
	var keyCode = e.which ? e.which : e.keyCode
	var ret = ( keyCode== 46 ||  ($(".numeric").val().length == 2)  || ($(".numeric").val().length == 0 && keyCode >= 48 && keyCode <= 53 ) || specialKeys.indexOf(keyCode) != -1);
	if (ret) {
		$(this).next().remove();
	} 
	else {
	   alert('error');
	}
	return ret;
});

Note: It will allows value like 2.9/3.4 etc but not 3.99 if you need it the it logic needs to change.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900