How to call a variable from other functions in JavaScript? [duplicate] - javascript

This question already has answers here:
Accessing variables from other functions without using global variables
(10 answers)
Closed 8 years ago.
I am trying to compute the total cost and using alert to display the total cost when the user hit the Submit button. I don't know how to call a var from other functions. Is there a way to do it? Any help will be appreciated. Thank you!
<script type = "text/javascript">
function CostCalculate(){
var TotalCost = AppleCost + OrangeCost + BananaCost;
alert("Your total cost is $ " + TotalCost);
}
function getQuantity1(){
var promptNum = prompt("Enter numbers of Apple: ");
var AppleNum = parseInt(promptNum);
var AppleCost = AppleNum * 0.59;
}
function getQuantity2(){
var promptNum = prompt("Enter numbers of Orange: ");
var OrangeNum = parseInt(promptNum);
var OrangeCost = OrangeNum * 0.49;
}
function getQuantity3(){
var promptNum = prompt("Enter numbers of Banana: ");
var BananaNum = parseInt(promptNum);
var BananaCost = BananaNum * 0.39;
}

Helo, I think you should read something about the variables scope in javascript.
https://msdn.microsoft.com/en-us/library/ie/bzt2dkta(v=vs.94).aspx
You can't acces a variable that's declarated in another function. What you can do is defining the variable outside of the functions.

Related

How to replace dot with a comma in the number [duplicate]

This question already has answers here:
Javascript toFixed localized?
(4 answers)
Closed last month.
Hey dear Stackoverflow community,
I have a JS code that calculates various values ​​based on an input value. It is output with a dot, but it should be displayed with a comma.
How can I customize the code for this?
<script>
var input = document.getElementById("invest_input-1");
input.oninput = function() {
var out = ((input.value * 0.38));
document.getElementById('invest_output_result-1').innerHTML = out.toFixed(2);
var out = ((input.value * 0.032));
document.getElementById('invest_output_result-2').innerHTML = out.toFixed(2);
var out = ((input.value * 0.03));
document.getElementById('invest_output_result-3').innerHTML = out.toFixed(2);
var out = ((input.value * 0.13));
document.getElementById('invest_output_result-4').innerHTML = out.toFixed(2);
};
</script>
Thank you so much!
Kind regards, Fabian
Based on the user's locale:
new Intl.NumberFormat().format(3500)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat#basic_usage
You can use
out.toFixed(2).replace('.', ',');

Error with adding two strings in JavaScript [duplicate]

This question already has answers here:
How to force JS to do math instead of putting two strings together [duplicate]
(11 answers)
How to force addition instead of concatenation in javascript [duplicate]
(3 answers)
Closed 3 years ago.
I have the following error:
jquery-3.4.1.min.js:2 The specified value "24.164.83" is not a valid
number. The value must match to the following regular expression:
-?(\d+|\d+.\d+|.\d+)([eE][-+]?\d+)?
Code
var grossTotal = netPrice * vatTotal // Is OK - it multiplies values
but
var grossTotal = netPrice + vatTotal // It makes this error -
it doesn’t sum.
The easiest way to produce a number from a string is prepend with +
var grossTotal= +netPrice + +vatTotal;
Try this code:
var netPrice = 1.432;
var vatTotal = 14.423;
var grossTotal = parseFloat(netPrice) + parseFloat(vatTotal)// Change according to data type of netPrice and/or vatTotal
console.log(grossTotal);
Try with type conversion:
var answer = parseInt(netPrice ) + parseInt(vatTotal);
You can use this code, First format value using parseFloat
var netPrice = 2.3777;
var vatTotal = 1.3777;
var grossTotal = parseFloat(netPrice ) + parseFloat(vatTotal);
console.log(grossTotal);
var netPrice = 2;
var vatTotal = 1;
var grossTotal = parseInt(netPrice ) + parseInt(vatTotal);
console.log(grossTotal);
For more information about parseFloat
https://www.w3schools.com/jsref/jsref_parsefloat.asp

How can i fix my output will be 2 decimal Numbers ex:(.11) or it should be (.00) [duplicate]

This question already has answers here:
Formatting a number with exactly two decimals in JavaScript
(32 answers)
Closed 5 years ago.
i want to get the output "total_amounts" like,ex(255.545645 = 255.54) and (150 =150.00). This is my code
$('.topag').on('input', function(){
var parent = $(this).closest('.calt');
var totalAmt = parseFloat(parent.find('.totalpr').val());
var quantity = parseFloat($(this).val());
parent.find('.total_amount').text(totalAmt*quantity);
$('#total_amounts').val(totalAmt*quantity);
$('#total_amounts').val(total);
calcul_total_quatities();
How can i fix this issue.
var total = 23.64654465;
var total_dec = total.toFixed(2);
document.getElementById("load").innerHTML = total_dec;
<p id="load"></p>
You can use the toFixed() method. The details for this can be found at the following link. See code below for coding needed for your scenario
var totalqty = totalAmt*quantity;
var total = totalqty.toFixed(2);
document.getElementById("total_amounts").innerHTML = total;

In this example how would I make filenames appended with "0000"+1 instead of "0"+1? [duplicate]

This question already has answers here:
Is there a JavaScript function that can pad a string to get to a determined length?
(43 answers)
Closed 8 years ago.
I know this is a gimme, but I'm trying to make the filenames serialized with four digits instead of one. This function is for exporting PNG files from layers within Adobe Illustrator. Let me know if you ever need icons - much respect.
var n = document.layers.length;
hideAllLayers ();
for(var i=n-1, k=0; i>=0; i--, k++)
{
//hideAllLayers();
var layer = document.layers[i];
layer.visible = true;
var file = new File(folder.fsName + '/' +filename+ '-' + k +".png");
document.exportFile(file,ExportType.PNG24,options);
layer.visible = false;
}
Use util.printf (see the Acrobat API, page 720):
var file = new File(util.printf("%s/%s-%04d.png", folder.fsName, filename, k));
You can pad your number to the left and take the last four characters like this:
var i = 9;
var num = ("0000"+i);
var str = "filename"+(num.substring(num.length-4)); //filename0009
Or shorter
str = ("0000" + i).slice(-4)
Thanks to this question

how to pass a variable into an regular expression in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do you pass a variable to a Regular Expression JavaScript?
I need help to resolve the issue because the code fails due to
numLength[0]:
<html>
<body>
<script type="text/javascript">
function xyz(){
var predefLength = "5,5";
var number = "20";
var numLength = predefLength.split(",");
var result = /^[-+]?\d{0,numLength[0]}(\.\d{0,numLength[1]})?$/.test(number);
document.write(result);
}
</script>
</body>
</html>
Any help will appreciated.
Use the RegExp-constructor, like:
var pattern = new RegExp('pattern as a string', 'flags as a string');
Or:
var result = new RegExp('^[-+]?\d{0,' + numLength[0] + '}(\.\d{0,' + numLength[1] + '})?$').test(number);
try this:
<script type="text/javascript">
function xyz(){
var predefLength = "5,5";
var number = "20";
var numLength = predefLength.split(",");
var pattern = new RegExp('^[-+]?\\d{0,'+numLength[0]+'}(\\.\\d{0,'+numLength[1]+'})?$');
var result = pattern.test(number);
document.write(result);
}
</script>
numLength[0] is 5. We can not add evaluation of variable in regular expression. Below code returns true.
var result = /^[-+]?\d{0,x}(\.\d{0,5})?$/.test(number);

Categories