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 badges4 Answers
Reset to default 3Use 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));
});
});