I have written HTML \ JavaScript code. The HTML page getting the three details from the end user. Based on the input from the user i want that javascript generate the barcode numbers and download the report as txt file. Here variable "B12" is a Barcode number.
Code is shown here :
const AL = document.getElementById("N1").value;
var to = Number(document.getElementById("N3").value);
var i = 1
var barcode = "1" + document.getElementById("N2").value;
while (i < to) {
const myArray = barcode.split("");
let B1 = myArray[1] * 8
let B2 = myArray[2] * 6
let B3 = myArray[3] * 4
let B4 = myArray[4] * 2
let B5 = myArray[5] * 3
let B6 = myArray[6] * 5
let B7 = myArray[7] * 9
let B8 = myArray[8] * 7
let B9 = B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8
let B10 = B9 % 11
let B11 = 11 - B10
B11 = B11 === 10 ? '0' : B11;
B11 = B11 === 11 ? '5' : B11;
rem = barcode.substring(1);
let B12 = AL + rem + B11 + "IN"
i++;
barcode++;
}
<form id="my-form">
<label for="T1">BARCODE FIRST TWO CHARATER</label><br><br>
<input type="" text " maxlength="2 " onkeyup="this.value=t his.value.toUpperCase(); " id="N1 " onchange="validity.valid||(value='' ) " required> <br><br>
<label for="T2 ">Barode Starting Eight Numbers:</label><br><br>
<input type="text " pattern="[0-9]{8} " maxlength="8 " onchange="validity.valid||(value='' ) " id="N2 " required ><br><br>
<label for="T3 ">Number of Barcode (Max 1000):</label><br><br>
<input type="number " id="N3 " min="1 " max="1000 " onchange="validity.valid||(value='' ) " required ><br><br>
<center><button type="submit " name="myButton ">Submit</button></center>
</form>
I want that javascript loop generate the report with the variable value "B12" and download as a text file while user click on submit button. Please help in the matter.
Maybe you can try that...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Barcode Number Generaot</title>
<style>
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 18px;
}
legend { font-weight: bold; padding: 0 .8em; }
fieldset { margin: 1em; width: 15em; }
label, input, button, pre { display: block; float: left; clear: both; margin-top: 0.2em; }
label { margin-top: 0.7em; font-size: .9em;}
input { text-align: center; }
button { margin-top: 2em; width: 6em; }
fieldset button:last-of-type { clear: none; float: right; }
pre { font-family: 'Courier New', Courier, monospace; font-size: 12px; margin: .8em;}
</style>
</head>
<body>
<form id="my-form" action="#">
<fieldset>
<legend>BarCode</legend>
<label>1st TWO characters</label>
<input name="N1" type="text" autocomplete="off" pattern="[A-Za-z0-9]{2}" required >
<label>1st Eight digits:</label>
<input name="N2" type="number" min="1" max="99999998" required >
<label>Number of Barcode (Max 1000):</label>
<input name="N3" type="number" min="1" max="10000" required value="1">
<button type="reset">clear</button>
<button type="submit">generate</button>
</fieldset>
</form>
<label>Generated BarCodes:</label>
<pre id="BC-genered"></pre>
<script>
const
CRcode = `\n` // carriage return
, writeToTextFile = (text, fileName) =>
{
let textFile = null;
const makeTextFile = (text) =>
{
const data = new Blob([text], { type: 'text/plain' });
if (textFile !== null)
{
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
let link = document.createElement('a');
link.setAttribute('download', fileName);
link.href = makeTextFile(text);
link.click();
}
, BCgen = document.querySelector('#BC-genered')
, myForm = document.querySelector('#my-form')
, digtsM = [8,6,4,2,3,5,9,7]
;
myForm.N1.oninput = () =>
{
myForm.N1.value = myForm.N1.value.toUpperCase();
if (myForm.N1.value.length > 2)
myForm.N1.value = myForm.N1.value[0] + myForm.N1.value[2];
}
myForm.N3.oninput = () =>
{
let N2_max = 99999999 - myForm.N3.valueAsNumber;
if ( myForm.N2.valueAsNumber > N2_max)
myForm.N2.valueAsNumber = N2_max;
myForm.N2.max = N2_max;
}
myForm.onreset = () =>
{
BCgen.textContent = '';
}
myForm.onsubmit = e =>
{
e.preventDefault() // disable submit (no page reloading in this case)
BCgen.textContent = '';
let B_1_8_CodeN = myForm.N2.valueAsNumber;
for (let i=myForm.N3.valueAsNumber; i--;)
{
let
Bcode = B_1_8_CodeN.toString(10).padStart(8, '0')
, B11 = 11 - ([...Bcode].map((x,i)=> x *digtsM[i]).reduce((sum,v)=>sum+v) % 11)
;
B11 = (B11 === 10) ? 0 : ( B11 === 11) ? 5 : B11;
BCgen.textContent += myForm.N1.value
+ Bcode
+ B11
+ 'IN'
+ CRcode;
B_1_8_CodeN++;
}
writeToTextFile(BCgen.textContent, `${myForm.N3.value}_Barcodes_${myForm.N1.value}_${myForm.N2.value}.txt`);
}
</script>
</body>
</html>
Related
Basically, I have a function that creates N input fields based on user choice, then I want to get those inputs for processing later on, though for some reason it creates a copy of the return over and over again, unless I add something like "conj.pop()" in the return. I wouldn't like to work not knowing why it only works if I pop the last one.
I put a console.log to keep track and the returned array was something like this:
Array(3)
0: 'A'
1: 'B'
2: (3) ['A','B','Array(3)]
If you expand this last array it repeats infinitely this very same description.
OBS: The inputs I've been using were simple 2,2 and A B, C D.
OBS2: The code wasn't previously in english so I translated some stuff, and left other small ones as they were variables only.
document.getElementById("ok1").onclick = () => {
const esp_qtd = document.getElementById("esp_qtd").value;
const car_qtd = document.getElementById("car_qtd").value;
document.getElementById("parte1").classList.add("invisivel");
document.getElementById("parte2").classList.remove("invisivel");
console.log(esp_qtd, car_qtd);
const generateFields = (tipo) => {
const qtd = document.getElementById(tipo + "_qtd").value;
const parent = document.getElementById(tipo + "_lista");
for (let i = 0; i < qtd; i++) {
const input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("id", (tipo + i));
parent.appendChild(input);
if (qtd > 5) {
if (((i + 1) % 3) == 0) parent.appendChild(document.createElement("br"));
}
console.log(i);
}
}
generateFields("esp");
generateFields("car");
const inputFields = (tipo, conj) => {
const qtd = document.getElementById(tipo + "_qtd").value;
for (let i = 0; i < qtd; i++) {
conj[i] = document.getElementById(tipo + i).value;
console.log("Iteration: " + i, conj);
}
return conj;
}
document.getElementById("ok2").onclick = () => {
const conjE = [];
const conjC = [];
conjE.push(inputFields("esp", conjE));
conjC.push(inputFields("car", conjC));
console.log(conjE);
console.log(conjC);
}
}
* {
font-family: 'Roboto', sans-serif;
font-size: 14pt;
margin-top: 1rem;
}
.invisivel {
display: none;
}
label {
margin-top: 1rem;
}
input {
margin-top: 0.5rem;
margin-right: 1rem;
margin-bottom: 0.5rem;
}
button {
margin-top: 1rem;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DOC</title>
<link rel="stylesheet" href="style.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
</head>
<body>
<div class="container">
<!-- PART 1 -->
<div id="parte1">
<form>
<label>N1</label><br>
<input type="text" id="esp_qtd"><br>
<label>N2</label><br>
<input type="text" id="car_qtd"><br>
<button id="ok1" type="button">OK</button>
</form>
</div>
<!-- PART 2 -->
<div id="parte2" class="invisivel">
<div id="esp_lista">
<label>ELEMENTS 1</label><br>
</div>
<div id="car_lista">
<label>ELEMENTS 2</label><br>
</div>
<button id="ok2" type="button">OK</button>
</div>
</div>
<script src="index.js"></script>
</body>
</html>
Please change your JS as follows:
document.getElementById("ok1").onclick = () => {
const esp_qtd = document.getElementById("esp_qtd").value;
const car_qtd = document.getElementById("car_qtd").value;
document.getElementById("parte1").classList.add("invisivel");
document.getElementById("parte2").classList.remove("invisivel");
console.log(esp_qtd, car_qtd);
const generateFields = (tipo) => {
const qtd = document.getElementById(tipo + "_qtd").value;
const parent = document.getElementById(tipo + "_lista");
for (let i = 0; i < qtd; i++) {
const input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("id", tipo + i);
parent.appendChild(input);
if (qtd > 5) {
if ((i + 1) % 3 == 0) parent.appendChild(document.createElement("br"));
}
console.log(i);
}
};
generateFields("esp");
generateFields("car");
const inputFields = (tipo, conj) => {
const qtd = document.getElementById(tipo + "_qtd").value;
console.log("Conj:" + qtd);
for (let i = 0; i < qtd; i++) {
conj[i] = document.getElementById(tipo + i).value;
console.log("Iteration: " + i, conj);
}
return conj;
};
document.getElementById("ok2").onclick = () => {
const conjE = [];
const conjC = [];
inputFields("esp", conjE);
inputFields("car", conjC);
console.log(conjE);
console.log(conjC);
};
};
I have only removed conjE.push() and conjC.push().
Explanation:
You are passing an array to store your data in it. But you're also returning the same array and storing it in it again. This creates an infinite loop of values. Either pass the variable or return the list.
Just did a simple game of checkers, got the logic done of jumping or moving the checker pieces.
Now having problems on the actual logic of when a checker piece moves over or jumps over the other checker piece. How do i automatically remove or delete the checker piece that was jumped over?
Thanks so much :)
<html>
<head>
<style>
body { background-color: #D1CDDF; }
p { font-family: Verdana, Geneva, sans-serif;
font-size: 30; }
img { width: 35px;
height: 35px; }
label { font-family: "Lucida Console", Monaco, monospace;
font-size: 15; }
.focused{ border: 2px solid yellow; }
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
var moves = [];
function saveScore() {
// syntax: $.post(URL,data,callback);
$.post("scores.php",
{
TheFile: $("#filename").val(),
TheMessage: $("#winner").val() + "\r\n"
}
,function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
function openBoard()
{
$(document).ready(function()
{
var p1Name = document.getElementById("p1name").value;
var p2Name = document.getElementById("p2name").value;
var heading = "<center><p><font color=\"red\"><b>" + p1Name + "</b></font> vs <font color=\"blue\"><b>" + p2Name + "</b></font></p></center>";
var table = $('<table width=500px cellspacing=0px cellpadding=0px border=1px ></table>');
var rc;
var picName;
var picName2;
for( y = 1; y <= 8; y++ )
{
var row = $('<tr></tr>');
for ( var x = 1; x <= 8; x++)
{
rc = y + x;
// creating the images
picName = "p" + 1 + ".png" ;
var pic1 = $('<img>').attr('src',picName);
picName2 = "p" + 2 + ".png";
var pic2 = $('<img>').attr('src',picName2);
if(rc % 2 === 0)
{
if(y === 1 || y === 2 || y === 3)
{
var col1 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
col1.html(pic1);
row.append(col1);
}
else if(y === 6 || y === 7 || y === 8)
{
var col2 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
col2.html(pic2);
row.append(col2);
}
else
{
var col3 = $('<td align=center height=50px width=50px bgcolor=#4E9660 ></td>').attr('id',y + '-' + x);
row.append(col3);
}
}
else
{
var col4 = $('<td align=center height=50px width=50px bgcolor=#C4C160 ></td>');
row.append(col4);
}
}
table.append(row);
}
document.getElementById("bBoard").style.visibility = "hidden";
$('#board').append(heading);
$('#board').append(table);
// setting the listener
$('td').click(function()
{
iAmtheClickListener(this.id);
});
});
}
function iAmtheClickListener(theID)
{
var r = $.inArray(theID,moves); // determine if the id is in the array
var content = $("#"+theID).html();
if( ((r < 0) && (content !== "")) || ((r<0) && (moves.length == 1)) )
{
moves.push(theID);
//change background color
changeBackground("#"+theID,"yellow");
}
else
{
moves.splice(r,1); // to remove
changeBackground("#"+theID,"#4E9660") ;
}
if (moves.length == 2)
{
var destId = moves[1] ;
var srcId = moves[0] ;
var srcImg = $("#" + srcId).html();
$("#" + destId).html(srcImg);
$("#" + srcId).html("");
moves = [] ; // remove all
changeBackground("#"+destId,"#4E9660") ;
changeBackground("#"+srcId,"#4E9660") ;
}
$('#result').html(theID);
}
function changeBackground(theIdUwant, theColor)
{
$(theIdUwant).css("background-color",theColor);
}
</script>
</head>
<body>
<center>
<p>~Checkers~</p>
<table border=1 cellpadding=25px>
<tr><td><label>Player 1: <input type=text id=p1name /></label><br/><br/>
<label>Player 2: <input type=text id=p2name /></label><br/><br/>
<button id="bBoard" onclick="openBoard();">Start Game</button><br/><br/></td>
<td><div class="b" id="board"></div></td>
<td>
<input type=hidden id=filename value="players.txt" />
<label>Register Winner: <input type=text id=winner /></label><br/><br/>
<button id="bReg" onclick="saveScore();">Submit</button><br/><br/>
<div id="result"></div>
</td>
</td></tr>
</table>
</center>
</body>
Suppose jumped piece is at board[row][col], you can assign a value of zero or empty at that particular cell after being jumped:
board[row][col] = EMPTY
I'm completely new nopCommerce. One of my client is getting error during check out with VISA card. He is getting the following screen. I'm not sure where do I start to troubleshoot. Can you please help me? Some how I'm not able to post exact HTML document. But please consider below code as properly formatted HTML.
<script type="text/javascript">
(function (f, b) {
if (!b.__SV) {
var a, e, i, g;
window.mixpanel = b;
b._i = [];
b.init = function (a, e, d) {
function f(b, h) {
var a = h.split(".");
2 == a.length && (b = b[a[0]], h = a[1]);
b[h] = function () {
b.push([h].concat(Array.prototype.slice.call(arguments, 0)))
}
}
var c = b;
"undefined" !== typeof d ? c = b[d] = [] : d = "mixpanel";
c.people = c.people || [];
c.toString = function (b) {
var a = "mixpanel";
"mixpanel" !== d && (a += "." + d);
b || (a += " (stub)");
return a
};
c.people.toString = function () {
return c.toString(1) + ".people (stub)"
};
i = "disable track track_pageview track_links track_forms register register_once alias unregister identify name_tag set_config people.set people.set_once people.increment people.append people.track_charge people.clear_charges people.delete_user".split(" ");
for (g = 0; g < i.length; g++) f(c, i[g]);
b._i.push([a, e, d])
};
b.__SV = 1.2;
a = f.createElement("script");
a.type = "text/javascript";
a.async = !0;
a.src = "//cdn.mxpnl.com/libs/mixpanel-2.2.min.js";
e = f.getElementsByTagName("script")[0];
e.parentNode.insertBefore(a, e)
}
})(document, window.mixpanel || []);
var mode = 'prd'.toLowerCase();
var token = '';
if (mode == 'demo') {
token = 'xxxxxxxxxxxxxxxxxxxxxx';
} else if (mode == 'prd' || mode == 'prda' || mode == 'prdk') {
token = 'xxxxxxxxxxxxxxxxxxxxxx';
} else if (mode == 'test') {
token = 'xxxxxxxxxxxxxxxxxxx';
} else {
token = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
}
if (token != '') {
mixpanel.init(token, {
persistence: 'localStorage'
});
}
</script><!-- end Mixpanel -->
<script type="text/javascript">
if (self !== top && typeof mixpanel !== "undefined") {
mixpanel.track("inFrame", {
"merchant_id": "XXXX(actual number here)",
"tid": "XXXX(actual number here)"
});
}
</script>
<style type="text/css">
BODY, TD, INPUT, SELECT, TEXTAREA, BUTTON, .normal {
font-family: arial,helvetica,sans-serif;
font-size: 10pt;
font-weight: normal;
}
.small {
font-size: 10pt;
}
.medium {
font-size: 14pt;
}
.large {
font-size: 18pt;
}
</style>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- process-transaction-response -->
<html>
<head>
<meta http-equiv="refresh" content="1;url=http://www.myvirtualmerchant.com?
ssl_approval_code=++++++&
ssl_cvv2_response=&
ssl_exp_date=XXXX(actual number here)&
ssl_account_balance=0.00&
ssl_get_token=&
ssl_token=&
ssl_departure_date=&
ssl_token_response=&
ssl_result_message=DECLINED&
ssl_invoice_number=XXXX(actual number here)&
ssl_description=Name1+Name2&
ssl_amount=184.48&
ssl_txn_id=GUID&
ssl_result=1&
ssl_card_number=XXXX(actual number here)&
ssl_completion_date=&
ssl_txn_time=10%2F28%2F2016+04%3A03%3A18+PM&
ssl_avs_response=G">
<style type="text/css">
BODY, TD, INPUT, SELECT, TEXTAREA, BUTTON, .normal {
font-family: arial,helvetica,sans-serif;
font-size: 10pt;
font-weight: normal;
}
.small {
font-size: 10pt;
}
.medium {
font-size: 14pt;
}
.large {
font-size: 18pt;
}
</style>
</head>
<form name="frmMenu" action="#" method="POST">
<input type="hidden" name="dispatchMethod" />
<input type="hidden" name="permissionDesc" />
<input type="hidden" name="menuAction" />
<input type="hidden" name="thClientID" value="" />
</form> <!-- start Mixpanel -->
</body>
</html>
I have a field that reads your lawn takes a ___ hour shower. It is calculated by the square footage input. When the value of this field equals 8,11,or 18. I would like it to read "an ____ hour shower." How would this be made possible?
http://jsfiddle.net/on6c360o/
var a = document.getElementById("a");
var b = document.getElementById("b");
var astored = a.getAttribute("data-in");
var g = document.getElementById("g");
setInterval(function() {
if (a == document.activeElement) {
var temp = a.value;
if (astored != temp) {
astored = temp;
a.setAttribute("data-in", temp);
calculate();
}
}
}, 10);
function calculate() {
b.innerHTML = a.value * .62;
g.innerHTML = Math.round(a.value * .0103);
}
<div class="mobile" style="text-align:center">
<h2>Lawn Square Footage</h2>
<input id="a" onkeypress="return isNumberKey(event)" style="height: 250px; margin-top: 10px; width: 75%; text-align: center; font-size: 100px;" type="text" data-in="" />
<h2>Water Usage</h2>
<h2 id="b">___</h2>
<h2>Gallons per day</h2>
<h2>Your lawn takes <span id="g">___</span> hour showers</h2>
</div>
You can use a ternary operator to say if hours is 8, 11, or 18 then display an else display a.
var hours = Math.round(a.value * .0103);
g.innerHTML = (hours === 8 || hours === 11 || hours === 18 ? 'an' : 'a') + ' ' + hours;
Here's an example http://jsfiddle.net/bmec3tad/
You could perform an if check when changing the HTML contents like so:
function calculate() {
b.innerHTML = a.value * .62;
var gVal = Math.round(a.value * .0103);
g.innerHTML = gVal + ([8, 11, 18].indexOf(gVal) == -1 ? "a" : "an");
}
Im new in javascript and I'm trying to make a simple currency converter, it is working fine when I select "£Pound" "£Pound" or "£Pound" "R$Real" but when I select "R$Real" "R$Real" runs the "Pound" "R$Real" calculation.
I spent hours trying to figure this out (very frustrating).
How to fix it? Is there another way to do it? (also tried using " if " and " else if " same issue). Thanks!
Here`s the HTML:
<label>Amount:</label>
<input type="text" id="amount" />
<label>From:</label>
<select id="select1">
<option value="pound">£ Pound</option>
<option value="real">R$ Real</option>
</select>
<label>To:</label>
<select id="select2">
<option value="pound">£ Pound</option>
<option value="real">R$ Real</option>
</select>
<input type="button" onClick="calculation()" value="calculate" />
<div id="result"></div>
Here`s the JS:
function calculation() {
var amount = document.getElementById('amount').value;
var currency1 = document.getElementById('select1').value;
var currency2 = document.getElementById('select2').value;
switch((currency1)&&(currency2)){
case "pound":
case "pound":
var y = amount * 1;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "pound":
case "real":
var x = currency2 = 3.40;
var y = amount * x;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real":
case "real":
var y = amount * 1;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real":
case "pound":
var x = currency2 = 3.40;
var y = amount / x;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
}}
To fix your JS do the following:
The issue is that your switch would compute to a single string, and you are using fall-through switch statements, jsFiddle to demonstrate what I mean.
Switch Statement Documentation for JavaScript
function calculation() {
var amount = document.getElementById('amount').value;
var currency1 = document.getElementById('select1').value;
var currency2 = document.getElementById('select2').value;
switch (currency1 + ' ' + currency2) {
case "pound pound":
var y = amount * 1;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "pound real":
var x = currency2 = 3.40;
var y = amount * x;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real real":
var y = amount * 1;
document.getElementById('result').innerHTML = "R$ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
break
case "real pound":
var x = currency2 = 3.40;
var y = amount / x;
document.getElementById('result').innerHTML = "£ " + parseFloat(Math.round(y * 100) / 100).toFixed(2);
}
}
Use the below to display the number and then just put the symbol in front, as this code will add commas and separators in the right spots, including negative.
Format number to currency:
function formatCurrency(num, precision) {
//identify '(123)' as a negative number
if (typeof num == 'string' && num.toString().indexOf('\\(') >= 0) {
num = '-' + num;
}
if (num === '' || (num === '-' && precision === -1)) {
return;
}
// if the number is valid use it, otherwise clean it
if (isNaN(num)) {
// clean number
if (num === '' || (num === '-' && precision === -1)) {
return;
}
if (isNaN(num)) {
num = '0';
}
}
// evalutate number input
var numParts = String(num).split('.');
var isPositive = (num == Math.abs(num));
var hasDecimals = (numParts.length > 1);
var decimals = (hasDecimals ? numParts[1].toString() : '0');
var originalDecimals = decimals;
// format number
num = Math.abs(numParts[0]);
num = isNaN(num) ? 0 : num;
if (precision >= 0) {
decimals = parseFloat('1.' + decimals); // prepend "0."; (IE does NOT round 0.50.toFixed(0) up, but (1+0.50).toFixed(0)-1
decimals = decimals.toFixed(precision); // round
if (decimals.substring(0, 1) == '2') {
num = Number(num) + 1;
}
decimals = decimals.substring(2); // remove "0."
}
num = String(num);
for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
}
if ((hasDecimals && precision == -1) || precision > 0) {
num += '.' + decimals;
}
// format symbol/negative
var format = isPositive ? '%s%n' : '(%s%n)';
var money = format.replace(/%s/g, '$');
money = money.replace(/%n/g, num);
return money;
}
console.log(formatCurrency(12002031203120, 2))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
<style>
body{
background:linear-gradient(3150deg,#7458ff,#a48afc);
background-size: cover;
height: 800px;
display: flex;
align-items: center;
justify-content:center;
}
.col-md-8{
background-color: rgb(183, 170, 170);
padding: 10px 24px;
border-radius: 20px;
width: 490px;
}
.form-group{
width: 100%;
display: flex;
}
input{
width:95%;
color:aliceblue;
height: 40px;
font-size: 1em;
margin: 0.2em 0;
border-radius: 10px;
border: none;
background: #676666;
outline: none;
padding: 0.1em;
}
select{
width: 50%;
height:40px;
font-size: 30px;
cursor: pointer;
background: #039cfb;
outline: none;
color: black;
padding: 0 1em;
border-radius: 10px;
border: none;
}
</style>
</head>
<body>
<div class="col-md-6 well">
<h3 class="text-primary">Javascript - Simple Currency Converter</h3>
<hr style="border-top:1px dotted #ccc;">
<div class="col-md-8">
<h4>Converter</h4>
<hr style="border-top:1px groovy #ccc;"/>
<div class="form-group">
<select onchange="Currency(); Calculate()" class="form-control" id="converter" style="width:30%;">
<option value="Dollar">Dollar</option>
<option value="Pound">Pound</option>
<option value="Euro">Euro</option>
<option value="Yen">Yen</option>
<option value="Yuan">Yuan</option>
</select>
<br />
<input type="number" oninput="Calculate()" class="form-control" id="value1"/>
</div>
<br /><br />
<div class="form-group">
<label>Pak Rupee:</label>
<input type="number" class="form-control" id="value2" disabled="disabled"/>
</div>
</div>
</div>
<script>
function Currency(){
y = document.getElementById("converter").value;
return y;
}
function Calculate(){
y = Currency();
x = document.getElementById("value1").value;
if(x == ""){
document.getElementById("value2").value = "";
}else{
switch(y){
case "Dollar":
document.getElementById("value2").value = x * 215.99;
break;
case "Pound":
document.getElementById("value2").value = x * 72.39;
break;
case "Euro":
document.getElementById("value2").value = x * 63.84;
break;
case "Yen":
document.getElementById("value2").value = x * 0.49;
break;
case "Yuan":
document.getElementById("value2").value = x * 8.20;
break;
}
}
}
</script>
</body>
</html>