0

I want to force the user to write in an input values, which have max 2 digits after "." For instance : 24.14 or 5.7 or 0.5 or 8 and NOT 4.321 or 5.133121. How can I do that ?

Attila Naghi
  • 2,535
  • 6
  • 37
  • 59
  • possible duplicate of [Force input to be decimal in @Html.Textbox](http://stackoverflow.com/questions/16646219/force-input-to-be-decimal-in-html-textbox) – neel shah Mar 19 '14 at 12:23
  • it's better to modify your question before moderator close it. – Fury Mar 19 '14 at 12:30

4 Answers4

3

I found a solution for this. You can use this api from Jquery: click here

Attila Naghi
  • 2,535
  • 6
  • 37
  • 59
0

You can't force any thing to any body but you could format it to decimal after user type

 <input type="text" id="input_id">

 //format decimal value while typing
(function($) {
    $.fn.currencyFormat = function() {
        this.each( function( i ) {
            $(this).change( function( e ){
                if( isNaN( parseFloat( this.value ) ) ) return;
                this.value = parseFloat(this.value).toFixed(2);
            });
        });
        return this; //for chaining
    }
})( jQuery );


$( function() {
    $("#input_id").currencyFormat();       
});

Resource

Community
  • 1
  • 1
Fury
  • 4,643
  • 5
  • 50
  • 80
0

You can make use of .toFixed() method which converts a number into a string, keeping a specified number of decimals.

sample:

var myNum = document.getElementById("textboxID").value;
myNum = parseFloat(myNum).toFixed(2); //I fixed my precision to 2 digits after "."
Navin
  • 594
  • 2
  • 11
0

This may work for you: here is the text input:

 <input type="text" id="tb1" >

And the JavaScript/JQuery code:

 $('#tb1').on('keydown',function(e){
 var textValue=document.getElementById('tb1').value;
if(textValue.indexOf('.')>=0 && e.which!=8 && e.which!=37 && e.which!=39 && e.which!=46)
   {
  textValue=textValue.split('.')[1];
   if(textValue.length>=2)
      return false;
   }
 });
durgesh.patle
  • 710
  • 6
  • 24