Javascript script does not log to browser console - javascript

I have a script but I can't figure out why it won't execute correctly.
I've declared all my variable and up to the prompts it works fine, but I can't see why it won't log the results of my functions.
var leasePriceString = prompt("Input lease price per month");
var ecoScoreString = prompt("Input eco score");
var catalogValueString = prompt("Input catalog value");
var c02String = prompt("Input C02");
var leasePrice = parseInt(leasePriceString);
var ecoScore = parseInt(ecoScoreString);
var catalogValue = parseInt(catalogValueString);
var c02 = parseInt(c02String);
var brutoMonth = true;
var VAA = true;
function calculator(){
function brutoMonthCalc(){
if (ecoScore >= 74){
brutoMonth = ((leasePrice*12)/13.92)-75;
console.log(brutoMonth);
} else {
brutoMonth = ((leasePrice*12)/13.92)-150;
console.log(brutoMonth);
}
}
function VAACalc(){
VAA = 6/7*catalogValue*(0.055+((c02-105)*0.001));
console.log(VAA);
}
brutoMonthCalc();
VAACalc();
console.log("price per month is =" + brutoMonth + VAA);
};
calculator();

I've modified some aspects of your code, and provided and explanation below:
var leasePriceString = prompt("Input lease price per month");
var ecoScoreString = prompt("Input eco score");
var catalogValueString = prompt("Input catalog value");
var c02String = prompt("Input C02");
var leasePrice = parseInt(leasePriceString);
var ecoScore = parseInt(ecoScoreString);
var catalogValue = parseInt(catalogValueString);
var c02 = parseInt(c02String);
// Declare global variables here
var brutoMonth;
var VAA;
function calculator(){
function brutoMonthCalc() {
if (ecoScore >= 74) {
brutoMonth = ((leasePrice * 12) / 13.92) - 75;
console.log(brutoMonth);
}else{
brutoMonth = ((leasePrice * 12) / 13.92) - 150;
console.log(brutoMonth);
}
}
function VAACalc() {
VAA = 6 / 7 * catalogValue * (0.055 + ((c02 - 105) * 0.001));
console.log(VAA);
}
// Call functions here
brutoMonthCalc();
VAACalc();
}
calculator();
console.log("price per month is =" + brutoMonth + VAA);
In the above code I mainly changed two things:-
Declaring global variables: You want to declare your variables only once, and then assign them in the functions that you intend to run to change their value.
Calling Functions: After you write a function, you need to call it later on. Only when you call it do the expressions in the function run.

Related

Invoking else statement every time

this is My code for adding a order details to the database. I want to check whether Stock Amount is higher or lower than Order Amount.So i put if statements on this. But every time it Invoke else statement. What is the wrong with this code
It Always Invoke Else Statement
function OrderAdd() {
var INameO = $("#INanme").text();
var IpriceO = $("#IPrice").text();
var IquantityO = $("#OQuntity").val();// order Amount
var Oquantity = $('#IQuantity').text(); //stock Amount
var Total = $("#IPrice").text() * $("#OQuntity").val();
if(Oquantity>IquantityO) {
addOrder(INameO, IpriceO, IquantityO, Total);
viewAllOrders();
gettotal();
clearItemArea();
console.log(IquantityO);
console.log(Oquantity);
}
else {alert("Amount exceeded")
}
}
function gettotal() {
var temptotal = 0;
var temp = getAllOrders();
for (var i = 0; i < temp.length; i++) {
var Total = temp[i].getOtotal();
temptotal = temptotal+Total;
$('#totalP').text(temptotal);
}
}
There is a one error. I didn't change values to the INT type. That's Why else Statement Invoking Every time. You can understand Better after watching this code.
function OrderAdd() {
var INameO = $("#INanme").text();
var IpriceO = parseInt( $("#IPrice").text());
var Oquantity =parseInt( $('#IQuantity').text()); //stock Amount
var IquantityO = parseInt($("#OQuntity").val());// order Amount
var Total = $("#IPrice").text() * $("#OQuntity").val();
//findduplicates(INameO);
if (Oquantity>IquantityO){
addOrder(INameO, IpriceO, IquantityO, Total);
viewAllOrders();
gettotal();
clearItemArea();
}
else{alert("Amount exceeded!")
}
}

If..else condition error

I am trying to figure out what is wrong with this following code. The code searches for value in a table and assigns mxCost. The IF..ELSE condition works for all values except 1 and is also reading the table. The IF condition makes the page crash and i am not able to figure out why? Can someone please help me figure out what i am doing wrong here. Any help will be appreciated. Thank you.
$jq("#airTableValues tbody tr").each(function() {
var monthName = months[parseInt(dateSplit[1])-1]+" "+dateSplit[0];
if(monthName==$jq(this).find("td:eq(0)").text().trim())
{
mxCost = $jq(this).find("td:eq(6)").text().trim();
}
});
if (mxCost)
mxCost = (mxCost.substring(1, mxCost.length));
else {
mxCost = 0;
}
var MxStat = document.getElementById("MxStat").value;
MxStat = MxStat/100;
var InflationRate1 = document.getElementById("InflationRate1").value;
InflationRate1 = InflationRate1/100;
var rate3 = document.getElementById("rate3").value;
rate3 = Math.pow(1+rate3/100,1/365)-1;
var mxAdj;
if (MxStat == 1){
mxAdj = mxCost;
} // <------- NOT WORKING!
else if (MxStat != 1) {
var TotalCost = mxCost * 2;
mxAdj = (TotalCost * MxStat) - mxCost;
}
var ReturnVal = (mxAdj * InflationRate1) + mxAdj;
var ReturnCalc = ReturnVal * 1000000;
var ReturnPV = Math.floor(ReturnCalc/Math.pow(1+rate3,periods));
document.getElementById("ReturnCondition").value =
(ReturnPV/1000000).toFixed(2);
ReturnCondition = ReturnVal.toFixed(2);
This worked for me
if (MxStat != 1){
var mxAdj = (TotalCost * MxStat) - mxCost;
var ReturnVal = (mxAdj * InflationRate1) + mxAdj;
aReturnCondition = ReturnVal.toFixed(2);
}
if (MxStat == 1){
var mxAdj = mxCost;
var ReturnVal = (mxAdj * InflationRate1) + mxAdj;
aReturnCondition = parseFloat(ReturnVal).toFixed(2);}

Why isn't my JavaScriptcode working with prompt and innerHTML?

Im trying to make an online Role Playing Game, but my code is not working. It asks the user what they want their character to be named, and what race they want to be. It would then randomly choose some stats for them, and -- depending upon their race -- add and subtract from their stats.
var nameAndRaceFunction = function(){
var namePrompt = prompt("What shall you name your character?");
var racePrompt = prompt("What race shall your character be? Please spell it correctly, with no capitals.");
var race = racePrompt.toLowerCase();
var totalSentence = namePrompt + " the " + race;
document.getElementById("nameAndRace").innerHTML = totalSentence;
}
var str = Math.floor((Math.random() * 10) + 1);
var int = Math.floor((Math.random() * 10) + 1);
var hlth = Math.floor((Math.random() * 10) + 1);
var dext = Math.floor((Math.random() * 10) + 1);
var getStatFunction = function(){
if(racePrompt === "elf"){
elfStats();
}else if(racePrompt === "dwarf"){
dwarfStats();
}else if(racePrompt === "man"){
manStats();
}else{
}
}
var elfStats = function(){
var elfStr = str;
var elfInt = int + 1;
var elfHlth = (hlth - 1)*10;
var elfDext = dext + 1;
document.getElementById("strength").innerHTML = elfStr;
document.getElementById("intelligence").innerHTML = elfInt;
document.getElementById("health").innerHTML = elfHlth;
document.getElementById("dexterity").innerHTML = elfDext;
}
var manStats = function(){
var manStr = str + 2;
var manInt = int;
var manHlth = (hlth - 1) * 10;
var manDext = dext;
document.getElementById("strength").innerHTML = manStr;
document.getElementById("intelligence").innerHTML = manInt;
document.getElementById("health").innerHTML = manHlth;
document.getElementById("dexterity").innerHTML = manDext;
}
var dwarfStats = function(){
var dwarfStr = str + 1;
var dwarfInt = int;
var dwarfHlth = (hlth + 1) * 10;
var dwarfDext = dext - 1;
document.getElementById("strength").innerHTML = dwarfStr;
document.getElementById("intelligence").innerHTML = dwarfInt;
document.getElementById("health").innerHTML = dwarfHlth;
document.getElementById("dexterity").innerHTML = dwarfDext;
}
racePrompt is defined inside the nameAndRaceFunction() function scope. It is not accessible outside of it. Further: you lower case it, so later I will check only for race not racePrompt.
One solution would be to make race global like str, int, hlth, dext
var nameAndRaceFunction = function() {
namePrompt = prompt("What shall you name your character?");
var racePrompt = prompt("What race shall your character be? Please spell it correctly, with no capitals.");
race = racePrompt.toLowerCase();
var totalSentence = namePrompt + " the " + race;
document.getElementById("nameAndRace").innerHTML = totalSentence;
getStatFunction()
}
var namePrompt, race;
var str = Math.floor((Math.random() * 10) + 1);
var int = Math.floor((Math.random() * 10) + 1);
var hlth = Math.floor((Math.random() * 10) + 1);
var dext = Math.floor((Math.random() * 10) + 1);
var getStatFunction = function() {
if (race === "elf") {
elfStats();
} else if (race === "dwarf") {
dwarfStats();
} else if (race === "man") {
manStats();
} else {
}
}
getStatFunction should be called with the race as argument or you should define the variable racePrompt outsite the function
Also, if you mean to make a player, a good idea should be have it as an object and use the nameAndRaceFunction like a constructor

Why does this code set the text to undefined?

Here is my JS function that sets the text to the variables. And how assign what Pokémon the player has.
function setStats() {
// Sets up stats based on Pokemon
if (computerPokemon === 'Pikachu') {
var computerAttack = 30;
var computerUlt = 60; // Does damage
var computerHealth = 50;
var computerSpeed = 20;
var computerAgility = 10;
}
if (playerPokemon === 'Ho-Oh') {
var playerAttack = 70;
var playerUlt = 10; // Buffs HP
var playerHealth = 80;
var playerSpeed = 35;
var playerAgility = 12;
}
document.getElementById("pHP").innerHTML = 'Health: ' + playerHealth;
document.getElementById("pSpeed").innerHTML = 'Speed: ' + playerSpeed;
document.getElementById("pAgility").innerHTML = 'Agility: ' + playerAgility;
}
function startGame() {
// Player Pokemon Selector
var playerPokemonArray = ["Ho-Oh","Venusaur","Weedle"];
var playerPokemonArrayRandom = Math.floor((Math.random() * playerPokemonArray.length));
var playerPokemon = playerPokemonArray[playerPokemonArrayRandom];
document.getElementById("playerPokemon").innerHTML = 'Your Pokemon is: ' + playerPokemon;
// Computer Pokemon Selector
var computerPokemonArray = ["Pikachu","Charmander","Diglett"];
var computerPokemonArrayRandom = Math.floor((Math.random() * computerPokemonArray.length));
var computerPokemon = computerPokemonArray[computerPokemonArrayRandom];
document.getElementById("computerPokemon").innerHTML = 'The Computer\'s Pokemon is: ' + computerPokemon;
When I run this code it sets the text of my stats paragraphs to undefined. Even though the variables are set depending on what Pokémon they were given.
I've tried changing my code around but nothing worked.
Your code is setting the stat variables from within the setStats() function, and you are trying to access them from startGame(). Javascript is a lexical scoped language. Since you are setting the variables from withink the function, only that function can access the variables. You can fix this by moving the variables into the global scope.
(Also, you are never calling the function setStats()

apply discounts to values in json javascript

I have an app with 3 items to purchase (3 books: wiz[0], lorax[1], and democrat[2]). These 3 books all cost $24.95, but two books cost $44.90(-$5 Off total), and three books cost $59.85(-$10 Off total). But the 4th or + book should be discounted to $19.95 with no further discounts. I am stuck on my third function "__totalWithDiscounts()". Does anyone have any idea how to do this? I feel like its super simple but I don't know what to do.
var cartJSON = [{'id':'wiz','count':0},
{'id':'gorax','count':0},
{'id':'democrat','count':0}]
function __updateTheTotal(item,quantity){
// find book being updated and change the count to the passed quantity
for (var i=0; i<cartJSON.length; i++) {
if (cartJSON[i].id == item) {
cartJSON[i].count = quantity;
break;
}
}
__totalWithDiscounts();
}
function __totalWithDiscounts(){
// this function will get the new json data generated by the inputs and apply discounts based on the amount
var discount_offTwoBooks = Number(5);
var discount_offThreeBooks = Number(10);
var priceOfEachBook_default = Number(24.95);
var priceOfEachBook_afterCountIs4 = Number(19.95);
var totalOf_wiz = Number(cartJSON[0].count);
var totalOf_gorax = Number(cartJSON[1].count);
var totalOf_democrat = Number(cartJSON[2].count);
var totalOf_all = +totalOf_wiz +totalOf_gorax +totalOf_democrat;
console.log('total books: '+totalOf_all);
}
I'd do this. Haven't tested this but pretty sure it'd work:
function __totalWithDiscounts(){
// this function will get the new json data generated by the inputs and apply discounts based on the amount
var discount_offTwoBooks = Number(5);
var discount_offThreeBooks = Number(10);
var priceOfEachBook_default = Number(24.95);
var priceOfEachBook_afterCountIs4 = Number(19.95);
var totalOf_wiz = Number(cartJSON[0].count);
var totalOf_gorax = Number(cartJSON[1].count);
var totalOf_democrat = Number(cartJSON[2].count);
var totalOf_all = 0+totalOf_wiz +totalOf_gorax +totalOf_democrat;
console.log('total books: '+totalOf_all);
var priceOfAll = 0;
if(totalOf_all >=4 ) priceOfAll = totalOf_all * priceOfEachBook_afterCountIs4;
else if(totalOf_all == 3) priceOfAll = priceOfEachBook_default * 3 - discount_offThreeBooks;
else if(totalOf_all == 2) priceOfAll = priceOfEachBook_default * 2 - discount_offTwoBooks;
else priceOfAll = priceOfEachBook_default * 1;
}
A bit of advice: use better variable names. And this was a simple logical construct of branching. Not that difficult to grasp: https://en.wikipedia.org/wiki/Conditional_(computer_programming)
Here's a jsfiddle with a solution: https://jsfiddle.net/6p1n1tta/3/
var totalOf_all = totalOf_wiz + totalOf_gorax + totalOf_democrat;
var discount = 0;
switch (totalOf_all) {
case 1: {
discount = 0;
break;
}
case 2: {
discount = discount_offTwoBooks;
break;
}
case 3: {
discount = discount_offThreeBooks;
break;
}
default: {
discount = priceOfEachBook_afterCountIs4;
break;
}
}
var totalPrice = (totalOf_all * priceOfEachBook_default) - discount;
console.log('total books: ' + totalOf_all + '\n' + 'total price: ' + totalPrice);
Also, in your __updateTheTotal function, it should be cartJSON[i].count += quantity;. The count won't properly update until you make that change.

Categories