My text field value format is 00.00. If i enter 4 digit number(1234), my text field should be automatically adjust 12.34 format. How to achieve this action in javascript on keyup?
Asked
Active
Viewed 3,829 times
4 Answers
1
You can try this code:
<script>
function round_off(mystring){
//alert(mystring);
mystring=mystring.replace(/\./g,'');
mystring = mystring.substring(0, 4);
mystring1 = mystring.substring(0, 2);
mystring2 = mystring.substring(2, 4);
mystring2=""+mystring1+"."+mystring2+"";
//alert(mystring2);
if(mystring!="" && mystring.length>2){
document.getElementById("round_no").value=mystring2;
}
}
</script>
<input type="text" id="round_no" value="" maxlength="5" onkeyup="round_off(this.value)">

Vikas Umrao
- 2,800
- 1
- 15
- 23
-
Its working fine on keyup. but keydown the value not removing properly. @Vikas – Sathya Jul 29 '15 at 09:54
1
Try RegEx:
$(function() {
$('input[type=text].two').on('input propertychange', function(e) {
this.value = this.value.replace(/\D/g, '').replace(/(\d{2})(\d*)/, '$1.$2');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" autofocus='' class='two' />
<input type="text" class='two' />
Here, .replace(/\D/g, '')
will give you only digits and .replace(/(\d{2})(\d*)/, '$1.$2')
will split your value with dot separator
0
Thats not how it works. if the format is 00.00 then it will just end up 1234.00

Kimtho6
- 6,154
- 9
- 40
- 56
0
this has already been handled here: How to print a number with commas as thousands separators in JavaScript
// for now as provided by the chosen answer in the above link: replace (\d{3}) with 2,
but actually i would need to know more of what the actual goal is , why u want to format it that way, etc in order to give a complete (valid) answer. But just take a read in the link above

Community
- 1
- 1

Danillo Felixdaal
- 585
- 4
- 11