最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - add .00 at the end of value while typing - Stack Overflow

programmeradmin2浏览0评论

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=".1.1/jquery.min.js"></script>
<input type="text">

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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">

Hope you can help me.

Thanks.

Share Improve this question asked Jun 28, 2018 at 11:34 Mark Gerryl MirandillaMark Gerryl Mirandilla 8231 gold badge21 silver badges44 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 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();
    }
});

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)

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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="text" />

i think you should try focusout event..

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

         var val = parseInt($(this).val());
         $(this).val(val.toFixed(2));
     });
});
发布评论

评论列表(0)

  1. 暂无评论