javascript automatic format when fill input - javascript

I have used a input like that:
<input type="text" onkeypress="maskDexxtz(this,maskCPF)" maxlength='14' title="<?php echo $this->__('Tax/VAT number') ?>"/>
I want to format input when customer type as: xxx.xxx.xxx-xx
My js code:
<script type="text/javascript">
function maskCPF(v) {
v = v.replace(/\D/g, "");
v = v.replace(/(\d{3})|(\.{1}d{3})/g, "$1.$2");
return v;
}
function maskDexxtz(o, f) {
v_obj = o
v_fun = f
setTimeout('mask()', 1)
}
function mask() {
v_obj.value = v_fun(v_obj.value)
}
</script>
However I just make it as xxx.xxx.xxx but can't capture two last key -xx.
Anywho can help me for it?

Here is a working version. I don't think there is a way to do this with regex replace.
$('input').on('keypress', (e, el) => {
mask(e.currentTarget);
})
function mask(el) {
timeout = setTimeout(() => {
el.value = el.value.replace(/\D/g, "");
let parts = el.value.match(/(\d{1,3})?(\d{1,3})?(\d{1,3})?(\d{1,2})?/);
el.value = '';
for(let i = 1; i <= 4; i++) {
if(parts[i] !== undefined) {
el.value += parts[i];
if(parts[i+1] !== undefined) {
el.value += i < 3 ? '.' : '';
el.value += i == 3 ? '-' : '';
}
}
}
}, 1);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" onkeypress="" maxlength='14' title="Tax/VAT number"/>

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"

How disable javascript effect on separated input field?

This is the Javascript that turns on Georgian keyboard in every input and textarea field
But I have one input field with ID user_login which type is text and of course, this javascript takes effect on this field too
I simply want to disable the effect of this javascript only for this field which ID is user_login
Please help me
thank you in advance
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="jquery.geokbd.css">
<script type="text/javascript" src="/js/jquery_min.js"></script>
<script type="text/javascript" src="jquery.geokbd.js"></script>
</head>
<body>
<div class="gk-switcher">
<input id="kbd-switcher" type="checkbox">
</div>
<form>
<input type="text" placeholder="Title">
<input type="text" placeholder="Description">
<input placeholder="Password" type="password">
<input placeholder="Email" type="email">
</form>
<input placeholder="Email" type="email">
<input placeholder="About me" maxlength="11" type="text">
<input placeholder="Username:" type="text" name="user_login" id="user_login" class="wide">
<script>
$('#kbd-switcher').geokbd();
</script>
</body>
</html>
and code
(function($, undefined) {
$.fn.geokbd = function(options) {
var
isOn,
inputs = $([]),
switchers = $([]),
defaults = {
on: true,
hotkey: '`'
},
settings = (typeof options === 'object' ? $.extend({}, defaults, options) : defaults);
// first come up with affected set of input elements
this.each(function() {
var $this = $(this);
if ($this.is(':text, textarea')) {
inputs = inputs.add($this);
} else if ($this.is('form')) {
inputs = inputs.add($this.find(':text, textarea'));
} else if ($this.is(':checkbox')) {
if (!inputs.length) {
inputs = $(':text, textarea');
}
switchers = switchers.add($this); // store the checkboxes for further manipulation
}
if (typeof settings.exclude === 'string') {
inputs = inputs.not(settings.exclude);
}
});
// mutate switchers
switchers
.click(function() { toggleLang() })
.wrap('<div class="gk-switcher"></div>')
.parent()
.append('<div class="gk-ka" /><div class="gk-us" />');
// turn on/off all switchers
toggleLang(isOn = settings.on);
$(document).keypress(function(e) {
var ch = String.fromCharCode(e.which), kach;
if (settings.hotkey === ch) {
toggleLang();
e.preventDefault();
}
if (!isOn || !inputs.filter(e.target).length) {
return;
}
kach = translateToKa.call(ch);
if (ch != kach) {
if (navigator.appName.indexOf("Internet Explorer")!=-1) {
window.event.keyCode = kach.charCodeAt(0);
} else {
pasteTo.call(kach, e.target);
e.preventDefault();
}
}
});
function toggleLang() {
isOn = arguments[0] !== undefined ? arguments[0] : !isOn;
switchers
.each(function() {
this.checked = isOn;
})
.closest('.gk-switcher')[isOn ? 'addClass' : 'removeClass']('gk-on');
}
// the following functions come directly from Ioseb Dzmanashvili's GeoKBD (https://github.com/ioseb/geokbd)
function translateToKa() {
/**
* Original idea by Irakli Nadareishvili
* http://www.sapikhvno.org/viewtopic.php?t=47&postdays=0&postorder=asc&start=10
*/
var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
for (var i = 0; i < this.length; i++) {
chr = this.substr(i, 1);
if ((index = symbols.indexOf(chr)) >= 0) {
text.push(String.fromCharCode(index + 4304));
} else {
text.push(chr);
}
}
return text.join('');
}
function pasteTo(field) {
field.focus();
if (document.selection) {
var range = document.selection.createRange();
if (range) {
range.text = this;
}
} else if (field.selectionStart != undefined) {
var scroll = field.scrollTop, start = field.selectionStart, end = field.selectionEnd;
var value = field.value.substr(0, start) + this + field.value.substr(end, field.value.length);
field.value = value;
field.scrollTop = scroll;
field.setSelectionRange(start + this.length, start + this.length);
} else {
field.value += this;
field.setSelectionRange(field.value.length, field.value.length);
}
};
}
}(jQuery));
If you call your plugin on the form element, instead of the checkbox and then search the document for all desired element types except the one with the id of user_login, your inputs JQuery wrapper will only contain the elements you want.
(function($, undefined) {
$.fn.geokbd = function(options) {
var
isOn,
inputs = $([]),
switchers = $([]),
defaults = {
on: true,
hotkey: '`'
},
settings = (typeof options === 'object' ? $.extend({}, defaults, options) : defaults);
// first come up with affected set of input elements
// Using the standard DOM API, search the document for all `input` and
// 'textarea' elements, except for the one with an id of: "user_login"
document.querySelectorAll("input:not(#user_login), textarea").forEach(function(item) {
var $this = $(item);
// You had the selector for an input incorrect
if ($this.is('input[type="text"], textarea')) {
inputs = inputs.add($this);
} else if ($this.is('form')) {
inputs = inputs.add($this.find('input[type="text"], textarea'));
} else if ($this.is(':checkbox')) {
if (!inputs.length) {
inputs = $('input[type="text"], textarea');
}
switchers = switchers.add($this); // store the checkboxes for further manipulation
}
if (typeof settings.exclude === 'string') {
inputs = inputs.not(settings.exclude);
}
});
// mutate switchers
switchers
.click(function() { toggleLang() })
.wrap('<div class="gk-switcher"></div>')
.parent()
.append('<div class="gk-ka" /><div class="gk-us" />');
// turn on/off all switchers
toggleLang(isOn = settings.on);
$(document).keypress(function(e) {
var ch = String.fromCharCode(e.which), kach;
if (settings.hotkey === ch) {
toggleLang();
e.preventDefault();
}
if (!isOn || !inputs.filter(e.target).length) {
return;
}
kach = translateToKa.call(ch);
if (ch != kach) {
if (navigator.appName.indexOf("Internet Explorer")!=-1) {
window.event.keyCode = kach.charCodeAt(0);
} else {
pasteTo.call(kach, e.target);
e.preventDefault();
}
}
});
function toggleLang() {
isOn = arguments[0] !== undefined ? arguments[0] : !isOn;
switchers
.each(function() {
this.checked = isOn;
})
.closest('.gk-switcher')[isOn ? 'addClass' : 'removeClass']('gk-on');
}
// the following functions come directly from Ioseb Dzmanashvili's GeoKBD (https://github.com/ioseb/geokbd)
function translateToKa() {
/**
* Original idea by Irakli Nadareishvili
* http://www.sapikhvno.org/viewtopic.php?t=47&postdays=0&postorder=asc&start=10
*/
var index, chr, text = [], symbols = "abgdevzTiklmnopJrstufqRySCcZwWxjh";
for (var i = 0; i < this.length; i++) {
chr = this.substr(i, 1);
if ((index = symbols.indexOf(chr)) >= 0) {
text.push(String.fromCharCode(index + 4304));
} else {
text.push(chr);
}
}
return text.join('');
}
function pasteTo(field) {
field.focus();
if (document.selection) {
var range = document.selection.createRange();
if (range) {
range.text = this;
}
} else if (field.selectionStart != undefined) {
var scroll = field.scrollTop, start = field.selectionStart, end = field.selectionEnd;
var value = field.value.substr(0, start) + this + field.value.substr(end, field.value.length);
field.value = value;
field.scrollTop = scroll;
field.setSelectionRange(start + this.length, start + this.length);
} else {
field.value += this;
field.setSelectionRange(field.value.length, field.value.length);
}
};
}
$('form').geokbd();
}(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="jquery.geokbd.css">
</head>
<body>
<div class="gk-switcher">
<input id="kbd-switcher" type="checkbox">
</div>
<form>
<input type="text" placeholder="Title">
<input type="text" placeholder="Description">
<input placeholder="Password" type="password">
<input placeholder="Email" type="email">
</form>
<input placeholder="Email" type="email">
<input placeholder="About me" maxlength="11" type="text">
<input placeholder="Username:" type="text" name="user_login" id="user_login" class="wide">
</body>
</html>

Javascript toLocaleString onKeyUp Event

I need some help to fix this issue, I'm trying to print out value from <input> tag while typing, and it should print out with thousand separator, but it return number like I input, more precisely it doesn't work. How I have to fix this...?
function cDes(e) {
var k = e.currentTarget;
var prc = k.value; //example value: 123456789
var prc_f = prc.toLocaleString('de-DE');
var oDiv = document.getElementById('cOut');
if (e.keyCode == 13) {
if (prc.length < 1) {
oDiv.innerHTML = 'FREE';
} else {
oDiv.innerHTML = prc_f; //expected output value: 123.456.789
}
} else {
oDiv.innerHTML = '...';
}
}
<input type='number' id='price' onKeyUp='cDes(event)'>
<div id='cOut'></div>
Convert the input string to Number before using Number.toLocaleString():
var prc_f = Number(prc).toLocaleString('de-DE');
Example:
// get a reference to the element once
var oDiv = document.getElementById('cOut');
function cDes(e) {
var prc = e.target.value; //example value: 123456789
if (e.keyCode == 13) {
if (prc.length < 1) {
oDiv.innerHTML = 'FREE';
} else {
// you only need to convert the input when you display it
oDiv.innerHTML = Number(prc).toLocaleString('de-DE'); //expected output value: 123.456.789
}
} else {
oDiv.innerHTML = '...';
}
}
<input type='number' id='price' onKeyUp='cDes(event)'>
<div id='cOut'></div>
This answer may deviate a little from your expectation , but you if objective is to show the price along with symbol , you can use Intl.NumberFormat
function cDes(e) {
var k = e.currentTarget;
var prc = k.value; //example value: 123456789
var prc_f = nf.format(prc);
var oDiv = document.getElementById('cOut');
if (e.keyCode == 13) {
if (prc.length < 1) {
oDiv.innerHTML = 'FREE';
} else {
oDiv.innerHTML = prc_f; //expected output value: 123.456.789
}
} else {
oDiv.innerHTML = '...';
}
}
var nf = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 0,
maximumFractionDigits: 2
});
<input type='number' id='price' onKeyUp='cDes(event)'>
<div id='cOut'></div>

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>

Getting comma separated values into input field

I am struggling already for some time to create script that deletes and adds values to field. The point is that when I click on div - there will be images inside, it will copy part of its class to field, or remove if it's already copied there. All the values in field input_8_3 need to be comma separated without spaces except the last one and in case there is only one value there shouldn't be any comma. The same with field input_8_4, but there I need only erased values.
In addition I need divs to change class on click, one click to add class, another to remove it, but this is how far could I get with my issue.
I need this for deleting images in custom field in Wordpresses frontend. input_8_3 goes to meta and input_8_4 to array in function to delete chosen images.
Thanks in advance!
(function($){
$('.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','')+',';
var oldtext = $('#input_8_3').val();
$('#input_8_3').val(text+oldtext);
});
})(jQuery);
(function($){
$('div.thumbn').click(function() {
$(this).removeClass('chosen-img');
});
})(jQuery);
(function($){
$('.thumbn').click(function() {
$(this).addClass('chosen-img');
});
})(jQuery);
.thumbn {
width: 85px;
height: 85px;
background: #7ef369;
float: left;
margin: 10px;
}
.chosen-img.thumbn{background:#727272}
input{width:100%}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="input_8_3" readonly="" value="3014,3015,3016,3017,3018" class="form-control data_lable">
<input type="text" id="input_8_4" readonly="" value="" class="form-control data_lable">
<div class="user-profile-avatar user_seting st_edit">
<div>
<div class="thumbn" id="img-act-3014"></div>
<div class="thumbn" id="img-act-3015"></div>
<div class="thumbn" id="img-act-3016"></div>
<div class="thumbn" id="img-act-3017"></div>
<div class="thumbn" id="img-act-3018"></div>
</div>
</div>
EDIT: I changed value of input_8_3. All the numbers in img-act-**** and values in input_8_3 are the same on load.
I've made a JS of it working.
https://jsfiddle.net/jatwm8sL/6/
I've added these:
var array = [3008,3009,3010,3011,3012];
$("#input_8_3").val(array.join());
and changed your click functions to this
var array = [3008,3009,3010,3011,3012];
var array1 = [];
$("#input_8_3").val(array.join());
(function($){
$('div.thumbn').click(function() {
var text = $(this).attr("id").replace('img-act-','');
var oldtext = $('#input_8_3').val();
if ($(this).hasClass('chosen-img'))
{
$('#input_8_3').val(text+oldtext);
var index = array.indexOf(text);
if (index !== -1)
{
array.splice(index, 1);
}
array1.push(text);
$(this).removeClass('chosen-img');
}
else
{
array.push(text);
var index = array1.indexOf(text);
if (index !== -1)
{
array1.splice(index, 1);
}
$(this).addClass('chosen-img');
}
$("#input_8_3").val(array.join());
$("#input_8_4").val(array1.join());
console.log(array1);
});
})(jQuery);
Basically, you need to check if it has a class and then remove if it has and add it if it doesn't.
Also, it's better to use a javascript array than to play around with html values as you change javascript arrays while HTML should really just display them.
If anything is unclear, let me know and I'll try to explain myself better
var transformNumbers = (function () {
var numerals = {
persian: ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"],
arabic: ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"]
};
function fromEnglish(str, lang) {
var i, len = str.length, result = "";
for (i = 0; i < len; i++)
result += numerals[lang][str[i]];
return result;
}
return {
toNormal: function (str) {
var num, i, len = str.length, result = "";
for (i = 0; i < len; i++) {
num = numerals["persian"].indexOf(str[i]);
num = num != -1 ? num : numerals["arabic"].indexOf(str[i]);
if (num == -1) num = str[i];
result += num;
}
return result;
},
toPersian: function (str, lang) {
return fromEnglish(str, "persian");
},
toArabic: function (str) {
return fromEnglish(str, "arabic");
}
}
})();
document.getElementById('ApproximateValue').addEventListener('input', event =>
event.target.value = TolocalInt(event.target.value)
);
function TolocalInt(value)
{
if ((value.replace(/,/g, '')).length >= 9) {
value = value.replace(/,/g, '').substring(0, 9);
}
var hasZero = false;
var value = transformNumbers.toNormal(value);
var result = (parseInt(value.replace(/[^\d]+/gi, '')) || 0);
if (hasZero) {
result = '0' + (result.toString());
}
return result.toLocaleString('en-US');
}
<input id="ApproximateValue" name="ApproximateValue" type="text" maxlength="12" />

Categories