Reputation: 930
I am trying to remove text after numbers typed and add decimal
I have multiple input type="text"
where on keypress I am adding a comma in INR (Indian Rupee) standard but when I type more than three numbers the entire value is removed and '0' is added. Also my code is not allowing the decimal .00 number as it should. What am I doing wrong?
HTML:
<input name="txtMSExMarCardFee" type="number" id="txtMSExMarCardFee" class="Stylednumber">
<input name="txtMSExMarCardFee1" type="number" id="txtMSExMarCardFee1" class="Stylednumber">
<input name="txtMSExMarCardFee2" type="number" id="txtMSExMarCardFee2" class="Stylednumber">
JS:
$('input.Stylednumber').keyup(function(){
var x=$(this).val();
x=x.toString();
var afterPoint = '';
if(x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'),x.length);
x = Math.floor(x);
x=x.toString();
var lastThree = x.substring(x.length-3);
var otherNumbers = x.substring(0,x.length-3);
if(otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
$(this).val(res );
});
Upvotes: 1
Views: 3740
Reputation: 10627
Try using this:
$('input.Stylednumber').keyup(function(){
var t = $(this), v = t.val();
if(!v.match(/\.\d{2}$/)){
v += '.00';
}
v = parseFloat(v.replace(/,/g, ''));
if(!v){ // was not a number
t.val('0.00');
return false;
}
v = v.toFixed(2);
if(v.length > 6){
t.val(v.slice(0, -6).replace(/(/d{3})/, '$1,')+v.slice(-6));
}
else{
t.val(v);
}
});
Upvotes: 0
Reputation: 1536
This requires that you cleanup the input before you pass it to through the regex
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
$('input.Stylednumber').keyup(function() {
var input = $(this).val().replaceAll(',', '');
if (input.length < 1)
$(this).val('0.00');
else {
var val = parseFloat(input);
var formatted = inrFormat(input);
if (formatted.indexOf('.') > 0) {
var split = formatted.split('.');
formatted = split[0] + '.' + split[1].substring(0, 2);
}
$(this).val(formatted);
}
});
function inrFormat(val) {
var x = val;
x = x.toString();
var afterPoint = '';
if (x.indexOf('.') > 0)
afterPoint = x.substring(x.indexOf('.'), x.length);
x = Math.floor(x);
x = x.toString();
var lastThree = x.substring(x.length - 3);
var otherNumbers = x.substring(0, x.length - 3);
if (otherNumbers != '')
lastThree = ',' + lastThree;
var res = otherNumbers.replace(/\B(?=(\d{2})+(?!\d))/g, ",") + lastThree + afterPoint;
return res;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="txtMSExMarCardFee" type="text" id="txtMSExMarCardFee" class="Stylednumber">
<input name="txtMSExMarCardFee1" type="number" id="txtMSExMarCardFee1" class="Stylednumber">
<input name="txtMSExMarCardFee2" type="number" id="txtMSExMarCardFee2" class="Stylednumber">
Upvotes: 1