Computer
Computer

Reputation: 2227

Allow decimal in JQuery code

I have the below script:

<link rel="stylesheet" href="//code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>

 $(function () {
    $("#<%= txtAmount.ClientID %>").keydown(function (e) {
        if (e.shiftKey || e.ctrlKey || e.altKey) {
            e.preventDefault();
        } else {
            var key = e.keyCode;
            if (!((key == 8) || (key == 46) || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105))) {
                e.preventDefault();
            }
        }
    });

What i am trying to do is allow the decimal character (.) but prevent all other characters except for numbers so the only allowed characters are numbers and a decimal.

I read up on keycodes for JQuery which states 110, 190 is the decimal character but the above code allows those values, i read up on javascript which has 46 as the decimal keycode but removing that from the code above didnt work either. Could anyone advise?

Upvotes: 0

Views: 116

Answers (2)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

here is a chunk:

$(document).ready(function () {
  //called when key is pressed in textbox
  $("#quantity").keypress(function (e) {
     //if the letter is not digit then display error and don't type anything
     if (e.which != 8 && e.which != 0 && e.which.indexOf('.') != -1 && (e.which < 48 || e.which > 57)) {
        //display error message
        $("#errmsg").html("Digits Only").show().fadeOut("slow");
               return false;
    }
   });


});

Fiddle DEMO

For your code:

$(function () {
    $("#<%= txtAmount.ClientID %>").keydown(function (e) {
         //if the letter is not digit then display error and don't type anything
         if (e.which != 8 && e.which != 0  && e.which.indexOf('.') != -1 && (e.which < 48 || e.which > 57)) {
            //display error message
            $("#errmsg").html("Digits Only").show().fadeOut("slow");
                   return false;
        }
    });

   });

Upvotes: 0

adeneo
adeneo

Reputation: 318352

Seems like there should be an easier way to do that

$("#<%= txtAmount.ClientID %>").keypress(function (e) {
    if (!String.fromCharCode(e.which).match(/[\d.]/)) e.preventDefault();
});

FIDDLE

Upvotes: 1

Related Questions