Number on keyup add comma in INR standard - javascript

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?
JS Fiddle
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 );
});

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">

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);
}
});

Related

How to make a space in between words and letters in html?

I have a problem to auto separate when input field detect between words and letters in html. For example expected result, when I type "ABB9102", the input field auto change to "ABB 9102".
Below is my coding, this coding just can restrict in-front 3 characters, cannot detect between words and letters, if I type "ABCD9102", it cannot auto change to "ABCD 9102":
function space(str, after) {
if (!str) {
return false;
}
after = after || 3;
var v = str.replace(/[^\dA-Z]/g, ''),
reg = new RegExp(".{" + after + "}", "g");
return v.replace(reg, function(a) {
return a + ' ';
});
}
var el = document.getElementById('pin');
el.addEventListener('keyup', function() {
this.value = space(this.value, 3);
});
<input autocapitalize="off" autocorrect="off" maxlength=20 type="text" placeholder="type the pin" id="pin" name="pin" />
Hope someone can guide me on how to solve this problem. Thanks.
Not sure if this is what you want?
<input autocapitalize="off" autocorrect="off" maxlength=20 type="text" placeholder="type the pin" id="pin" name="pin" />
<script>
var el = document.getElementById('pin');
function make_space () {
var content = el.value;
var patt = content.match(/[^\d|^\s]\d/g);
var x;
if (patt != null)
for (x of patt) {
el.value = content.replace(x, x[0] + " " + x[1])
content = el.value;
}
var content = el.value;
var patt = content.match(/\d[^\d|^\s]/g);
var x;
if (patt != null)
for (x of patt) {
el.value = content.replace(x, x[0] + " " + x[1])
content = el.value;
}
}
el.addEventListener('keyup', make_space);
el.addEventListener('change', make_space);
</script>
function space(str) {
if (str) {
const getIntialThree = str.slice(0,3)
const restThreeLetter = str.slice(3)
const result = `${getIntialThree} ${restThreeLetter}`;
console.log(result)
}{
return false
}
}
// testing
const number = 'ABB9102'
space(number)
//output
> "ABB 9102"

Thousand separator while typing and decimal (with comma)

I have a problem.
$('#value-salary').on('keyup', function(){
if($(this).val() != ""){
var n = parseInt($(this).val().replace(/\D/g,''),10);
$(this).val(n.toLocaleString());
}
});
This allow me to see "." as thousand separator while typing. Before submit I will replace "." with "" and for now it's all ok.
The problem is that the keyup doesn't allow me to insert "," and I need to use this as decimal separator (before sending i will replace , with . but user is not interested in rest api. He want to see "," as decimal separator).
How can i fix this problem? Keypress or keydown are not good solutions...thanks!
you can use autoNumeric.js.
$(".testInput").autoNumeric('init', {
aSep: '.',
aDec: ',',
aForm: true,
vMax: '999999999',
vMin: '-999999999'
});
<input class="testInput" type="text" value="8000"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/autonumeric/1.8.2/autoNumeric.js"></script>
please see more information how to use numeric.
http://www.decorplanit.com/plugin/
You can try this piece of code. It places , as thousand separator and you can use . for your decimal separator. You can easily customize the symbols you want to use for each purpose.
<html>
<head>
<script language="javascript" type="text/javascript">
function thousandSeparator(n, sep) {
var sRegExp = new RegExp('(-?[0-9]+)([0-9]{3})'),
sValue = n + '';
if (sep == undefined) { sep = ','; }
while (sRegExp.test(sValue)) {
sValue = sValue.replace(sRegExp, '$1' + sep + '$2');
}
return sValue;
}
function showSeparator() {
var myValue = document.getElementById("txtInvoicePrice").value;
myValue = thousandSeparator(myValue.replace(/,/g, ""), ',');
document.getElementById("txtInvoicePrice").value = myValue;
}
function removeSeparator() {
var myValue = document.getElementById("txtInvoicePrice").value;
myValue = myValue.replace(',', '');
document.getElementById("txtInvoicePrice").value = myValue;
}
</script>
</head>
<body>
<input type="text" id="txtInvoicePrice" onfocus="javascript:removeSeparator();" onblur="javascript:showSeparator();" />
</body>
</html>
It works for me with javascript code:
<input type="text" name="xxx" onkeyup="ididit(this,this.value.charAt(this.value.length-1))" value=""/>
And:
<script>
function ididit(donde,caracter) {
pat = /[\*,\+,\(,\),\?,\\,\$,\[,\],\^]/
valor = donde.value
largo = valor.length
crtr = true
if(isNaN(caracter) || pat.test(caracter) == true) {
if (pat.test(caracter)==true) {
caracter = "\\" + caracter
}
carcter = new RegExp(caracter,"g")
valor = valor.replace(carcter,"")
donde.value = valor
crtr = false
} else {
var nums = new Array()
cont = 0
for(m=0;m<largo;m++) {
if(valor.charAt(m) == "," || valor.charAt(m) == " ") {
continue;
}else{
nums[cont] = valor.charAt(m)
cont++
}
}
}
var cad1="",cad2="",tres=0
var cad3="",cad4=""
if(largo > 3 && crtr == true) {
if (nums[0]=="$"){
nums.shift()
}
for (k=nums.length-1;k>=0;k--) {
cad1 = nums[k]
cad2 = cad1 + cad2
tres++
if((tres%3) == 0) {
if(k!=0){
cad2 = "," + cad2
}
}
if (k==0) {
cad2 = "$ " + cad2
}
}
donde.value = cad2
} else if (largo <= 3 && crtr == true) {
if (nums[0]=="$"){
nums.shift()
}
for (k=nums.length-1;k>=0;k--) {
cad3 = nums[k]
cad4 = cad3 + cad4
if (k==0) {
cad4 = "$ " + cad4
}
}
donde.value = cad4
}
}
</script>

jQuery phone number masking with Regex not working

I've been trying to mask the phone number into a region specific format.
$("input:text[name=phone_number]").keyup(function() {
var number = $(this).val().replace(/[^\d]/g, '');
number = number.replace(/(\d{3})(\d{3})(\d{3})/, "($1) $2-$3");
$(this).val(number);
});
The problem I am having with the script above is that regex is waiting for 3 numbers before it replaces the value in the input field.
And additionally I have to press enter for the effects to take place.
Is there a way I can make (\d{3}) this more dynamic. For example even if I've entered only 1 digit it should still display (0 ).
And then I continue entering (05 )... and so on...to a format that looks like this (051) 000-000?
I don't want to use additional plugins. I know there are many out there.
I made a simple mask, check:
$("input[name=phone_number]").keydown(function(e) {
var actualValue = e.key;
var baseMask = '(###) ###-###';
var valueInput = this.value.match(/\d/g);
if (actualValue !== 'Backspace' && /[^\d]/.test(actualValue)) {
return false;
}
if (actualValue === 'Backspace') {
if (!valueInput) {
return false;
}
valueInput.pop();
actualValue = '#';
}
var numsValues = valueInput ? valueInput.concat(actualValue) : [actualValue];
$.each(numsValues, function() {
baseMask = baseMask.replace(/\#/, this);
});
$(this).val(baseMask);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="phone_number">
$("#input").keyup(function() {
var number = $(this).val().replace(/[^\d]/g, "");
number = number.replace(/(\d{3})(\d{0,3})(\d{0,3})/, function(match, p1, p2, p3) {
if (p2.length < 1)
return "(" + p1 + ") ";
else if (p3.length < 1)
return "(" + p1 + ") " + p2;
return "(" + p1 + ") " + p2 + "-" + p3;
});
$(this).val(number);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" id=input placeholder="type your number">

If input field is empty fill it with random number

I want to fill all empty number fields with a random number. I can populate all fields with a random number as shown below.
$.each(numberField, function () {
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
});
But if I try and wrap it around an
if (numberField.val() === "")
It doesn't work
What am I doing wrong here? see fiddle
<input type="number" value="0">
<input type="number" value="">
<input type="number" value="4">
<input type="number" value="5">
<input type="number" value="">
var numberField = $('input[type=number]');
var x = '';
if (numberField.val() === "") {
$.each(numberField, function () {
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
});
}
You need to move your condition (you are looking if an array is equal to "", which is never the case). You also need to trim the value to check if it is really empty:
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
if ($.trim($(this).val()) === "") {
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
}
});
in your example numberField is an array so your code must be like this:
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
if ($(this).val() === "") {
x = Math.floor((Math.random() * 10) + 1);
$(this).val(x);
}
});
See the updated fiddle.
$.each(numberField, function (k, v) {
if ($(v).val() === "") {
x = Math.floor((Math.random() * 10) + 1);
($(v).val(x));
}
});
Take a look at the doc for the jQuery each function.
try this...
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
if (this.value === "") { // should check the value inside the loop.. not outside
x = Math.floor((Math.random() * 10) + 1);
this.value = x;
}
});
demo
I think the problem is here:
numberField.val()
instead, use
$(this).val()
so ...
var numberField = $('input[type=number]');
var x = '';
$.each(numberField, function () {
alert($(this).val());
if ($(this).val() === ""){
x = Math.floor((Math.random() * 10) + 1);
($(this).val(x));
};
});
updated Fiddle
http://jsfiddle.net/aaronk85/eC48k/
You can match only the fields with no value like this:
$('input[type=number][value=""]').each(function () {
this.value=Math.floor((Math.random() * 10) + 1);
});
Here's the demo.

JavaScript not being executed onClick

I have a webpage where I'm processing an HTML form using JavaScript and onClick, but the JavaScript code isn't being executed.
This is my form:
<form action="" method="post" id="reportform">
<input type="radio" name="report" value="customer"><p>Customers</p>
<input type="radio" name="report" value="item"><p>Items Sold</p>
<input type="radio" name="report" value="department"><p>Sales Departments</p>
<input type="radio" name="report" value="person"><p>Sales People</p>
<input type="button" name="reportsubmit" value="Submit" onClick="checkReport(this.form)">
</form>
And this is the JavaScript code (by this way both the JavaScript and the form are located in the body tag):
function checkReport (form)
{
var checked = form.querySelector('input:checked');
var value = checked ? checked.value : null;
if (value == "customer")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#customer" + href.slice(idx+19);
window.location.replace(new_href);
}
else if (value == "item")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#item" + href.slice(idx+19);
window.location.replace(new_href);
}
else if (value == "department")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#department" + href.slice(idx+19);
window.location.replace(new_href);
}
else if (value == "person")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#person" + href.slice(idx+19);
window.location.replace(new_href);
}
}
function checkCustomer(form)
{
var checked = form.querySelector('input:checked');
var value = checked ? checked.value : null;
if (value == "all")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#allcustomers" + href.slice(idx+19);
window.location.replace(new_href);
}
else if (value == "one")
{
var href = "http://bdpastudents.com/~a7068104/2013-2014/Lab_13/Reports/Reports.php";
var idx = href.indexOf("Reports", 0);
var new_href = href.slice(0,idx+19) + "#onecustomer" + href.slice(idx+19);
window.location.replace(new_href);
}
}
Your HTML is illegal. You have not closed your input tags. Who knew, you don't have to close your tags. Sorry about that.
Can you replicate your problem on this fiddle? Or does this work for you?
var form = document.getElementById('reportForm');
http://jsfiddle.net/mgDGN/

Categories