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>
Related
Over my head with javascript. I'm trying to get the cards to shuffle when clicking next.
Currently, it moves forward with one random shuffle and stops. Back and forward buttons then no longer work at that point.
Please help—many thanks.
When I'm lost and unsure what sample of the code to pinpoint, the captions go up to 499. The sample is also here: https://rrrhhhhhhhhh.github.io/sentences/
Very new to javascript. So any help is greatly appreciated. Very open to better ways to achieve this???
How I have it set up:
HTML:
var r = -1;
var mx = 499; // maximum
var a = new Array();
function AddNumsToDict(){
var m,n,i,j;
i = 0;
j = 0;
while (i <= 499)
{
m = (500 * Math.random()) + 1;
n = Math.floor(m);
for (j=0;j<=499;j++)
{
if (a[j] == (n-1))
{
j = -1;
break;
}
}
if (j != -1)
{
//a.push(n-1);
a[i] = (n-1);
i++;
j=0;
}
}
return;
}
function startup()
{
writit('SENTENCES<br><br><br>Robert Grenier', 'test');
SetCookie("pg", -1);
AddNumsToDict();
}
function SetCookie(sName, sValue)
{
document.cookie = sName + "=" + escape(sValue) + ";"
}
function GetCookie(sName)
{
// cookies are separated by semicolons
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
// a name/value pair (a crumb) is separated by an equal sign
var aCrumb = aCookie[i].split("=");
if (sName == aCrumb[0])
return unescape(aCrumb[1]);
}
// a cookie with the requested name does not exist
return null;
}
function doBack(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
//if ((oNxt) && (oPrev))
//{
var num = GetCookie("pg");
if (num == mx){ //maximum
SetCookie("pg",parseInt(num) - 1);
num = GetCookie("pg");
}
// oNxt.disabled = false;
// if (num <= 1){
// oPrev.disabled = true;
// }
if (num >= 1){
num--;
writit(Caption[a[num]], 'test');
SetCookie("pg",num);
}
//}
}
function doNext(){
//var oPrev = xbElem('prev');
//var oNxt = xbElem('nxt');
// if ((oNxt) && (oPrev))
// {
var num = GetCookie("pg");
// if (num > -1){
// oPrev.disabled = false;
// }
// else{
// oPrev.disabled = true;
// }
// if (num >= parseInt(mx)-1){ //maximum - 1
// oNxt.disabled = true;
// }
// else {
// oNxt.disabled = false;
// }
if (num <= parseInt(mx)-2){
num++;
writit(Caption[a[num]],'test');
SetCookie("pg",num);
}
// }
}
function writit(text,id)
{
if (document.getElementById)
{
x = document.getElementById(id);
x.innerHTML = '';
x.innerHTML = text;
}
else if (document.all)
{
x = document.all[id];
x.innerHTML = text;
}
else if (document.layers)
{
x = document.layers[id];
l = (480-(getNumLines(text)*8))/2;
w = (764-(getWidestLine(text)*8))/2;
text2 = '<td id=rel align="center" CLASS="testclass" style="font:12px courier,courier new;padding-left:' + w.toString() + 'px' + ';padding-top:' + l.toString() + 'px' + '">' + text + '</td>';
x.document.open();
x.document.write(text2);
x.document.close();
}
}
function getNumLines(mystr)
{
var a = mystr.split("<br>")
return(a.length);
}
function getWidestLine(mystr)
{
if (mystr.indexOf(" ") != -1)
{
re = / */g;
mystr = mystr.replace(re,"Z");
//alert(mystr);
}
if (mystr.indexOf("<u>") != -1)
{
re = /<u>*/g;
mystr = mystr.replace(re, "");
re = /<\/u>*/g;
mystr = mystr.replace(re, "");
}
if (mystr.indexOf("<br>") != -1)
{
var ss, t;
var lngest;
ss = mystr.split("<br>");
lngest = ss[0].length;
for (t=0; t < ss.length; t++)
{
if (ss[t].length > lngest)
{
lngest = ss[t].length;
}
}
}
else {
lngest = mystr.length;
}
return(lngest);
}
// -->
</script>
<body bgcolor="gainsboro" onload="startup();">
<table bgcolor="white" border height="480px" width="764px" cellpadding="0" cellspacing="0">
<tr>
<td align="center">
<table nowrap>
<tr>
<td><img width="700px" height="1px" src="./resources/images/w.gif"></td>
<td>
<div class="testclass" id="test"></div>
</td>
</tr>
</table>
</td>
</tr>
</table>
<center>
<form>
<p>
<input type="button" onclick="doBack(); return false" value="Back">
<input type="button" onclick="doNext(); return false" value="Next">
JS:
var _____WB$wombat$assign$function_____ = function(name) {return (self._wb_wombat && self._wb_wombat.local_init && self._wb_wombat.local_init(name)) || self[name]; };
if (!self.__WB_pmw) { self.__WB_pmw = function(obj) { this.__WB_source = obj; return this; } }
{
let window = _____WB$wombat$assign$function_____("window");
let self = _____WB$wombat$assign$function_____("self");
let document = _____WB$wombat$assign$function_____("document");
let location = _____WB$wombat$assign$function_____("location");
let top = _____WB$wombat$assign$function_____("top");
let parent = _____WB$wombat$assign$function_____("parent");
let frames = _____WB$wombat$assign$function_____("frames");
let opener = _____WB$wombat$assign$function_____("opener");
function CaptionArray(len) {
this.length=len
}
Caption = new CaptionArray(499);
Caption[0] = "leaf and the ants as latterly"
Caption[1] = "thought<br>living in<br>Davis would<br>be ok"
Caption[2] = "sure arm today"
Caption[3] = "AMY<br><br>no we<br>both do<br>different<br>songs together"
Caption[4] = "much of anything she doesn't like that at all"
Caption[5] = "SUNG AS LAKE<br><br><br>that never wanted back to come"
Caption[6] = "five sound shut doors"
Caption[7] = "oh<br>my nose is<br>so<br>red<br>Obediah<br>dear"
Caption[8] = "these<br>cubes<br>have been<br>on the floor"
Caption[9] = "sweating importunate"
Caption[10] = "all over noises phone rings"
Caption[11] = "I think this is the water supply for Lake Johnsbury"
Caption[12] = "Paw so greasy"
Caption[13] = "BLACK & WHITE RAIN<br><br><br>clear water grey drops<br><br><br>on windshields in a line<br><br><br>of cars progressing slowly<br><br><br>with windshield wipers wiping"
Caption[14] = "EMILY<br><br>Roger,<br><br>are you<br><br>thinking of me"
Caption[15] = "STICKS<br><br><br>rhythm is inside the sound like another"
Caption[16] = "I think their dog always barks when coming back from the woods"
Caption[17] = "weren't there<br><br>conversations"
Caption[18] = "LOOKING AT FIRE<br><br><u>ashes</u> to ashes<br><br>looking at the fire<br><br>at has been added"
Caption[19] = "a the bank"
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 months ago.
Improve this question
*This calculator is only for one digit calculations
In my code there are 3 textboxes Two for values and one for Operators.
I want that if first textbox isn't empty and user clicks on any number than that value should be added in another textbox.
When I click Enter it doesn't display result and I didn't show any kind of error in console
// Textboxes, Enter and Reset
var txt1 = document.querySelector("#txt1");
var txt2 = document.querySelector("#txt2");
var txt3 = document.querySelector("#txt3");
var ent = document.querySelector("#ent");
var res = document.querySelector("#res");
// Number-Buttons
var b1 = document.querySelector("#b1");
var b2 = document.querySelector("#b2");
var b3 = document.querySelector("#b3");
var b4 = document.querySelector("#b4");
var b5 = document.querySelector("#b");
var b6 = document.querySelector("#b6");
var b7 = document.querySelector("#b7");
var b8 = document.querySelector("#b8");
var b9 = document.querySelector("#b9");
// Operators
var add = document.querySelector("#add");
var sub = document.querySelector("#sub");
var mul = document.querySelector("#mul");
var div = document.querySelector("#div");
if (txt1.value == "") {
function B1() { txt1.value = "1" }
function B2() { txt1.value = "2" }
function B3() { txt1.value = "3" }
function B4() { txt1.value = "4" }
function B5() { txt1.value = "5" }
function B6() { txt1.value = "6" }
function B7() { txt1.value = "7" }
function B8() { txt1.value = "8" }
function B9() { txt1.value = "9" }
if (txt2.value == "") {
function Add() { txt2.value = "+" }
function Sub() { txt2.value = "-" }
function Mul() { txt2.value = "*" }
function Div() { txt2.value = "/" }
}
// if (txt1.value != "" && txt3.value == "") {
// function B1() { txt3.value = "1" }
// function B2() { txt3.value = "2" }
// function B3() { txt3.value = "3" }
// function B4() { txt3.value = "4" }
// function B5() { txt3.value = "5" }
// function B6() { txt3.value = "6" }
// function B7() { txt3.value = "7" }
// function B8() { txt3.value = "8" }
// function B9() { txt3.value = "9" }
// }
}
function Ent() {
if (txt1.value == "" || txt2.value == "" || txt3.value == "") {
alert("Pls Enter values and select the operator");
}
function sum() {
if (txt2.value == "+") {
var Sum = Number(txt1.value) + Number(txt3.value);
alert(Sum);
console.log(Sum);
}
}
function sub() {
if (txt2.value == "-") {
var Sub = Number(txt1.value) - Number(txt3.value);
alert(Sub);
console.log(Sub);
}
}
function mul() {
if (txt2.value == "*") {
var Mul = Number(txt1.value) * Number(txt3.value);
alert(Mul);
console.log(Mul);
}
}
function div() {
if (txt2.value == "/") {
var Div = Number(txt1.value) / Number(txt3.value);
alert(Div);
console.log(Div);
}
}
}
I tried to understand what you want to do from the code you shared. In the solution you developed, I made subtractions as the numbers are defined as separate buttons. In this direction, I developed a lean solution. This program is used as follows:
Use the numeric keypad to enter the first number.
Click the action you want to perform (+, -, *, /)
Use the numeric keypad to enter the second number.
Click the CALCULATE button to see the result.
Click the CLEAR button to clear the screen.
var firstNumberText = document.getElementById("txt1");
var secondNumberText = document.getElementById("txt2");
var operatorText = document.getElementById("txt3");
var operationText = document.getElementById("txt4");
var resultText = document.getElementById("txt5");
var addButton = document.getElementById("add");
var subButton = document.getElementById("sub");
var mulButton = document.getElementById("mul");
var divButton = document.getElementById("div");
var enterButton = document.getElementById("enter");
var clearButton = document.getElementById("clear");
let status = true;
let currentFirstNumber = "";
let currentSecondNumber = "";
function updateText(){
firstNumberText.innerText = currentFirstNumber;
secondNumberText.innerText = currentSecondNumber;
}
function changeState(operator) {
operatorText.innerText = operator;
status = !status;
}
addButton.addEventListener("click", function() {
changeState("+");
});
subButton.addEventListener("click", function() {
changeState("-");
});
mulButton.addEventListener("click", function() {
changeState("*");
});
divButton.addEventListener("click", function() {
changeState("/");
});
function numberPressed(pressedButton) {
if(status)
currentFirstNumber += pressedButton.value;
else
currentSecondNumber += pressedButton.value;
}
function updateResult(result, operator) {
operationText.innerText = firstNumberText.textContent + operator + secondNumberText.textContent + "=" + `${result}`;
resultText.innerText = result;
}
function calculate() {
if (firstNumberText.value == "" || secondNumberText.value == "" || operatorText.value == "") {
alert("Warning");
return;
}
var result = 0;
if(operatorText.textContent == "+") {
result = parseInt(firstNumberText.textContent) + parseInt(secondNumberText.textContent);
updateResult(result, "+");
}
else if(operatorText.textContent == "-") {
result = parseInt(firstNumberText.textContent) - parseInt(secondNumberText.textContent);
updateResult(result, "-");
}
else if(operatorText.textContent == "*") {
result = parseInt(firstNumberText.textContent) * parseInt(secondNumberText.textContent);
updateResult(result, "*");
}
else if(operatorText.textContent == "/") {
result = parseInt(firstNumberText.textContent) / parseInt(secondNumberText.textContent);
updateResult(result, "/");
}
}
enterButton.addEventListener("click", function() {
calculate();
});
clearButton.addEventListener("click", function() {
status = true;
currentFirstNumber = "";
currentSecondNumber = "";
firstNumberText.innerText = "";
secondNumberText.innerText = "";
operatorText.innerText = "";
operationText.innerText = "";
resultText.innerText = "";
});
<!-- First Number -->
<label id="txt1">-</label><br>
<!-- Operator -->
<label id="txt3">-</label><br>
<!-- Second Number -->
<label id="txt2">-</label><br>
<!-- Operation -->
<label id="txt4">-</label><br>
<!-- Result -->
<label id="txt5">-</label><br>
<button type="button" value="0" onclick='numberPressed(this);updateText()'>0</button>
<button type="button" value="1" onclick='numberPressed(this);updateText()'>1</button>
<button type="button" value="2" onclick='numberPressed(this);updateText()'>2</button>
<button type="button" value="3" onclick='numberPressed(this);updateText()'>3</button>
<button type="button" value="4" onclick='numberPressed(this);updateText()'>4</button>
<button type="button" value="5" onclick='numberPressed(this);updateText()'>5</button>
<button type="button" value="6" onclick='numberPressed(this);updateText()'>6</button>
<button type="button" value="7" onclick='numberPressed(this);updateText()'>7</button>
<button type="button" value="8" onclick='numberPressed(this);updateText()'>8</button>
<button type="button" value="9" onclick='numberPressed(this);updateText()'>9</button>
<br><br>
<button type="button" id="add">+</button>
<button type="button" id="sub">-</button>
<button type="button" id="mul">*</button>
<button type="button" id="div">/</button><br><br>
<button type="button" id="enter">CALCULATE</button>
<button type="button" id="clear">CLEAR</button>
I am working on a webapp, and the formatting of the one text field is working almost perfectly, however, the only thing that is happening I do not want to happen is when I click out of the field and there is no value, it returns NaN
HTML
<input type="text" class="rounded" name="sname" id="investamt" onblur="handleChange()"><br>
Javascript
var fnf = document.getElementById("investamt");
fnf.addEventListener('keyup', function(evt){
var n = parseInt(this.value.replace(/\D/g,''),10);
fnf.value = n.toLocaleString();
}, false);
function handleChange() {
var myValue = document.getElementById("investamt").value;
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("investamt").value = myValue;
}
Why is it returning NaN when I click out of the text field and it is blank, I would like it to return 0 instead, for example.
You can check the value and zero it out with if (isNaN(n)) n = 0;
var fnf = document.getElementById("investamt");
fnf.addEventListener('keyup', function(evt) {
var n = parseInt(this.value.replace(/\D/g, ''), 10);
if (isNaN(n)) n = 0;
fnf.value = n.toLocaleString();
}, false);
function handleChange() {
var myValue = document.getElementById("investamt").value;
if (myValue.indexOf("$") != 0) {
myValue = "$" + myValue;
}
document.getElementById("investamt").value = myValue;
}
<input type="text" class="rounded" name="sname" id="investamt" onblur="handleChange()"><br>
when you parse something empty string it will return NAN. try this on console:--
parseInt(''.replace(/\D/g,''),10)
try this code....
hope it will fill your requirments :)
var fnf = document.getElementById("investamt");
fnf.addEventListener('keyup', function(evt){
var n
n = this.value.replace(/\D/g,'')
fnf.value = n;
}, false);
function handleChange() {
var myValue = document.getElementById("investamt").value;
if(myValue.length === 0){ myValue = '0'}
if (myValue.indexOf("$") != 0)
{
myValue = "$" + myValue;
}
document.getElementById("investamt").value = myValue;
}
<input type="text" class="rounded" name="sname" id="investamt" onblur="handleChange()"><br>
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"/>
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>