0

I'm trying to validate user input data using jquery. Here is the code I use.

$('#ole').keypress(function(event) {
              if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
                event.preventDefault();
              }
            });

The code above allows only integers and a single dot. What I need is to allow only two integers after the dot.

How to achieve that ?

0

2 Answers 2

3

TRY with this

HTML

<input id="ole" class="decimal">​

jQuery

$(document).on('change blur','.decimal',function() {
      var amt = parseFloat(this.value);
      if(isNaN(amt)) {
        $(this).val('');
      }
      else {
         $(this).val(amt.toFixed(2));
      }
    });

working DEMO

Sign up to request clarification or add additional context in comments.

4 Comments

Only problem here is user may not expect automatic rounding, which might lead to input errors. In fact, if this is a "money" field, then any digits to the right of the penny are probably accidental. Nevertheless, +1 for the idea.
@AlexMa yes your are right, but rounding after 2 place look fine even in money format. isn't it so?
Thanks. Can you advice me how to combine your code with that I provide ?
write this code under <script> tag and add class .alnum on <input> tag. Note: use jquery 1.7
1

Use a Regex expression and round the decimals:

$('#ole').on('blur', function()
{
    var val = $(this).val();

    if (val.match(/^\d+\.{0,1}\d+$/)) 
    {
        // Convert to int if needed
        val = parseInt(val);

        val = Math.round(val *100)/100; // Round to 2 decimals
        $(this).val(val);
    }
});​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.