2

I'm working a simple field where only accepts numbers, what I want is to add ".00" at the end of the value while I'm typing. ex. 1000.00.

the problem I cant achieve that format, after 1 digit it adds '.00' and cant type anymore.

I tried the answer here but didn't work.

here is my sample work

$(document).ready(function(){
 $("input").keyup(function(){

        var val = parseInt($(this).val());
        $(this).val(val.toFixed(2));

    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">

Hope you can help me.

Thanks.

4 Answers4

3

Use blur function like this:

$("input").blur(function(){

    var val = parseInt($(this).val());
    if(val){
        $(this).val(val.toFixed(2));
    }else{
        $(this).val(0);
        $(this).focus();
    }
});
Sanoj_V
  • 2,936
  • 1
  • 12
  • 28
3

If what you want to do is type 1 and immediately get 1.00, then type 2 and you will get 12.00, then you need to save cursor position (like described here).

  • So you want to get current cursor position
  • format the input data
  • update input element
  • restore cursor position in needed place (depending on where it should be moved)
zmii
  • 4,123
  • 3
  • 40
  • 64
2

Try this:

$( 'input' ).on( 'input', function() {
  var val = $( this ).val(),
      arr = val.split( '.' );

  if ( arr.length > 1 )
    $( this ).val( arr[ 0 ] + val.substr( val.length - 1 ) + '.00' )
  else
    $( this ).val( val + '.00' )
} ).on( 'keypress', function( e ) {
  return e.charCode == 46 || ( e.charCode >= 48 && e.charCode <= 57 )
} )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" />
Kavian K.
  • 1,340
  • 1
  • 9
  • 11
1

i think you should try focusout event..

$(document).ready(function(){
     $("input").focusout(function(){

         var val = parseInt($(this).val());
         $(this).val(val.toFixed(2));
     });
});
Sanoj_V
  • 2,936
  • 1
  • 12
  • 28
jay vyas
  • 11
  • 3