I have a textbox and onkeyup event I have to mask (with asterisk (*) character) a portion of the string (which is a credit card number) when user enter the values one after the other. e.g. say the value that the user will enter is 1234 5678 1234 2367.
But the textbox will display the number as 1234 56** **** 2367
I general if the user enters XXXX XXXX XXXX XXXX, the output will be XXXX XX** **** XXXX where X represents any valid number
The program needs to be done using jQuery. I have already made the program (and it is working also) which is as follows:
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script>
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $(this).val();
var CCNLength = CCNValue.length;
$.each(CCNValue, function(i) {
if (CCNLength <= 7) {
$("#txtCCN").val(CCNValue);
} //end if
if (CCNLength >= 8 && CCNLength <= 14) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, CCNLength).replace(/[0-9]/g, "*"));
} //end if
if (CCNLength >= 15) {
$("#txtCCN").val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/[0-9]/g, "*") + CCNValue.substring(15));
} //end if
});
});
});
</script>
</head>
<body>
<input type="text" id="txtCCN" maxlength=19 />
</body>
</html>
But I think that the program can be optimized/re-written in a much more elegant way.
N.B. I don't need any validation at present.
No need of any condition of length, substring and replace can be directly used on the string of any length safely.
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
var CCNValue = $.trim($(this).val());
$(this).val(CCNValue.substring(0, 7) + CCNValue.substring(7, 15).replace(/\d/g, "*") + CCNValue.substring(15));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
val can also be used
$(document).ready(function() {
$("#txtCCN").keyup(function(e) {
$(this).val(function(i, v) {
return v.substring(0, 7) + v.substring(7, 15).replace(/\d/g, "*") + v.substring(15);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<input type="text" id="txtCCN" maxlength=19 />
The same can be done in VanillaJS
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('txtCCN').addEventListener('keyup', function() {
var value = this.value.trim();
this.value = value.substring(0, 7) + value.substring(7, 15).replace(/\d/g, '*') + value.substring(15);
}, false);
});
<input type="text" id="txtCCN" required maxlength="19" />
Try It: Its 100% workable...
$(document).ready(function () {
$("#txtCCN").keyup(function (e) {
var CCNValue = $(this).val();
CCNValue = CCNValue.replace(/ /g, '');
var CCNLength = CCNValue.length;
var m = 1;
var arr = CCNValue.split('');
var ccnnewval = "";
if (arr.length > 0) {
for (var m = 0; m < arr.length; m++) {
if (m == 4 || m == 8 || m == 12) {
ccnnewval = ccnnewval + ' ';
}
if (m >= 6 && m <= 11) {
ccnnewval = ccnnewval + arr[m].replace(/[0-9]/g, "*");
} else {
ccnnewval = ccnnewval + arr[m];
}
}
}
$("#txtCCN").val(ccnnewval);
});
});
One thing you might consider is deleting the first two if statements. All of the work your function does is contained within the last one, so you could just change it from
if(CCNLength >= 15)
to
if(CCNLength >= 8)
This seems to maintain the functionality while cutting out some repetition in your code.
Adding a generic routine for customizing space points and mask range in the input data. This will also respect the space characters as you originally asked for.
$(function () {
$("#cardnum").keyup(function (e) {
var cardNo = $(this).val();
//Add the indices where you need a space
addSpace.call(this, [4, 9, 14], cardNo );
//Enter any valid range to add mask character.
addMask.call(this, [7, 15], $(this).val()); //Pick the changed value to add mask
});
function addSpace(spacePoints, value) {
for (var i = 0; i < spacePoints.length; i++) {
var point = spacePoints[i];
if (value.length > point && value.charAt(point) !== ' ')
$(this).val((value.substr(0, point) + " "
+ value.substr(point, value.length)));
}
}
function addMask(range, value) {
$(this).val(value.substring(0, range[0])
+ value.substring(range[0], range[1]).replace(/[0-9]/g, "*")
+ value.substring(range[1]));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="cardnum" maxlength="19" />
Related
I want to replace a number over 100 with commas. Like 1000 to 1,000 and 1000000 to 1,000,000 etc. in HTML. I have found the code on here to do so but it only works with predetermined numbers being passed. I don't want it to work for a predetermined number but for any number typed into the box.
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>£ </span><input type="text" id="turnover" maxlength="11"
name="turnover" size="10" required>*
<br /><br />
<script type="text/javascript">
$('#turnover').keydown(function(){
var str = $(this).val();
str = str.replace(/\D+/g, '');
$(this).val(str.replace(/\B(?=(\d{3})+(?!\d))/g, ","));});
</script>
I created a solution using pure javascript.
function onChange(el) {
var newValue = el.value.replace(/,/g, '');
var count = 0;
const last = newValue.substring(newValue.length - 1, newValue.length); // last input value
// check if last input value is real a number
if (!isNumber(last)) {
el.value = el.value.substring(0, el.value.length - 1);
return;
}
newValue = newValue.split('')
.reverse().map((it) => {
var n = it;
if (count > 0 && count % 3 == 0) n = n + ',';
count++;
return n;
})
.reverse().join('')
el.value = newValue
// document.getElementById('value').innerHTML = newValue
}
function isNumber(input) {
return input.match(/\D/g) == undefined;
}
<label>Number</label>
<input id="numbers" onkeyup="onChange(this)">
There are a couple of issues with your code:
It runs once when the page loads, not after that. I added a button to fix that.
The id used in your code does not match the actual id of the input field.
Input fields must be read and written using .val(). .text() works only for divs, spans etc.
Note that the conversion now works one time, after that it fails to properly parse the new text which now contains the comma(s).
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function ShowComma() {
console.clear();
var val = parseInt($("#comma").val());
console.log(val);
val = numberWithCommas(val);
console.log(val);
$("#comma").val(val);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="turnover">Estimated Monthly Card Turnover:</label><br />
<span>£ </span><input type="value" id="comma" maxlength="30" name="turnover" size="10" required>*
<button onclick="ShowComma()">Show Comma</button>
To finalise this I have putgetElementById functions in so that this will work with a wordpress contact form 7. This must be with a text field though as it will not work with the number field as it will now accept commas:
<script>
document.getElementById("averagetrans").onkeyup = function() {onChange(this)};
document.getElementById("Turnover").onkeyup = function() {onChange(this)};
</script>
<script type="text/javascript">
function onChange(el) {
var newValue = el.value.replace(/,/g, '');
var count = 0;
const last = newValue.substring(newValue.length - 1, newValue.length); // last input value
// check if last input value is real a number
if (!isNumber(last)) {
el.value = el.value.substring(0, el.value.length - 1);
return;
}
newValue = newValue.split('')
.reverse().map((it) => {
var n = it;
if (count > 0 && count % 3 == 0) n = n + ','; // put commas into numbers 1000 and over
count++;
return n;
})
.reverse().join('')
el.value = newValue
// document.getElementById('value').innerHTML = newValue
}
function isNumber(input) {
return input.match(/\D/g) == undefined;
}
</script>
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>
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">
Console.log is showing the correct result, but how can I add the same formatting to the input type while typing.
Input type is reset after every comma to zero.
1000 to 1,000
Please Help.
This code is working here
function numberWithCommas(number) {
if (isNaN(number)) {
return '';
}
var asString = '' + Math.abs(number),
numberOfUpToThreeCharSubstrings = Math.ceil(asString.length / 3),
startingLength = asString.length % 3,
substrings = [],
isNegative = (number < 0),
formattedNumber,
i;
if (startingLength > 0) {
substrings.push(asString.substring(0, startingLength));
}
for (i=startingLength; i < asString.length; i += 3) {
substrings.push(asString.substr(i, 3));
}
formattedNumber = substrings.join(',');
if (isNegative) {
formattedNumber = '-' + formattedNumber;
}
document.getElementById('test').value = formattedNumber;
}
<input type="number" id="test" class="test" onkeypress="numberWithCommas(this.value)">
Some notes:
Because you want commas, the type is not a number, it's a string
Because you want to work on the input after you type, it's onkeyup not onkeypressed
I have a solution that does a regex replace for 3 characters with 3 characters PLUS a comma:
var x = "1234567";
x.replace(/.../g, function(e) { return e + ","; } );
// Gives: 123,456,7
i.e. almost the right answer, but the commas aren't in the right spot. So let's fix it up with a String.prototype.reverse() function:
String.prototype.reverse = function() {
return this.split("").reverse().join("");
}
function reformatText() {
var x = document.getElementById('test').value;
x = x.replace(/,/g, ""); // Strip out all commas
x = x.reverse();
x = x.replace(/.../g, function(e) { return e + ","; } ); // Insert new commas
x = x.reverse();
x = x.replace(/^,/, ""); // Remove leading comma
document.getElementById('test').value = x;
}
<input id="test" class="test" onkeyup="reformatText()">
function numberWithCommas(x) {
var real_num = x.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
console.log(real_num);
document.getElementById('test').value = real_num;
}
<input type="number" id="test" onkeypress="numberWithCommas(this.value)">
Check out my fiddle here http://jsfiddle.net/6cqn3uLf/
You'd need another regex to limit to numbers but this will format based on the user's locale - which may be advantageous here.
<input id="mytext" type="text">
$(function () {
$('#btnformat').on('input propertychange paste', function () {
var x = $('#btnformat').val();
$('#btnformat').val(Number(x.replace(/,/g,'')).toLocaleString());
});
});
if jquery is not overhead for your application then you can use
https://code.google.com/p/jquery-numberformatter/
$(document).ready(function(){
$("input").keyup(function(){
if($(this).val().split(' ').length == 10){
alert();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Enter your name: <input type="text">
If the input is 1 2 3 4 5 6 7 8 9 the alert fired, I know it included the space. But how to stop user from adding more character (even space) when the limit is reached?
The problem can easily be simplified to disabling the spacebar when the max word count is reached:
this should work: http://jsfiddle.net/wznervgz/6/
<input data-max-words="10" />
js:
$('input[data-max-words]').on('keydown', function (e) {
var $txt = $(this),
max = $txt.data('maxWords'),
val = $txt.val(),
words = val.split(' ').length;
if (words === max && e.keyCode === 32)
return false;
});
Hope this will help you.
<textarea name="txtMsg" id="word_count" cols="1" rows="1"> </textarea>
<span style="padding-left:10px;">Total word Count :
<span id="display_count" style="font-size:16px; color:black;">0</span> words &
<span id="count_left" style="font-size:16px; color:black;">2</span> words left.</span>
<br>
jquery code:
var max_count = 2;
$(document).ready(function () {
var wordCounts = {};
$("#word_count").keyup(function () {
var matches = this.value.match(/\b/g);
wordCounts[this.id] = matches ? matches.length / 2 : 0;
var finalCount = 0;
$.each(wordCounts, function (k, v) {
finalCount += v;
});
var vl = this.value;
if (finalCount > max_count) {
vl = vl.substring(0, vl.length - 1);
this.value = vl;
}
var countleft = parseInt(max_count - finalCount);
$('#display_count').html(finalCount);
$('#count_left').html(countleft);
am_cal(finalCount);
});
}).keyup();
Fiddle link: http://jsfiddle.net/aVd4H/32/
Thank you.
Think about storing the value of the input after each keyup and if the wordcount is greater than your limit just setVal back to the "previously" saved amount. So it would start off as var previousVal = ''; and then increment accordingly until the comparison returns true, set the val and return.
Demo: http://jsfiddle.net/robschmuecker/wznervgz/1/
$(document).ready(function(){
var previousValue = '';
$("input").keydown(function(){
if($(this).val().split(' ').length >= 10){
alert();
$(this).val(previousVal);
return;
}
previousVal = $(this).val();
});
});
You can try this:
$("input").keydown(function(e){
if($(this).val().split(' ').length == 10){
alert();
e.preventDefault();
return false;
}