Salary Calculation Function in JavaScript not working - javascript

From the input on the HTML, the user inputs the employee name and a number of hours they worked. From here on the submit button it takes the information and stores it in the variables so that I can calculate how much their pay was. Now with this also comes the overtime pay. I thought this was on the right track but whenever I go back to my HTML it displays "undefined". Any suggestions?
//Global Variables
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;
function paySalary() {
if (employeeHours <= 40) {
var regtime = 11.00 * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (11.00 * 40);
var overtime = ((11.00 * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
document.getElementById("results").innerHTML = "Employee Name: " + employeeName + " | Employee Gross Pay: " + salary;
}
//Event Listener to Submit
var submitButton = document.getElementById("submit");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", paySalary, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", paySalary);
}
Screenshot of output

Look at the scope of your salary variable, it's defined inside the if-else block. Make your salary variable accessible to document.getElementById() by declaring it in your function like this:
<html>
<script>
function paySalary() {
var employeeName = document.getElementById("name").value;
var employeeHours = document.getElementById("hours").value;
if (employeeHours <= 40) {
var regtime = 11.00 * employeeHours;
var overtime = 0.00;
var salary = regtime;
} else if (employeeHours > 40) {
var regtime = (11.00 * 40);
var overtime = ((11.00 * 1.5) * (employeeHours - 40));
var salary = (regtime + overtime);
}
document.getElementById("name").innerHTML = "Employee Name: " + employeeName;
document.getElementById("pay").innerHTML = "Employee Gross Pay: " + salary;
}
</script>
<body>
<input id="name" value="Kamesh Dashora"></input>
<input id="hours" value=40></input>
<br>
<span id="pay">0</span>
<br>
<button id="submit" onclick="paySalary()">Submit</button>
<body>
</html>

Related

Why won't nothing show. Did I mess up my if statement?

So I have this script that get 2 prices, and then finds the sum of it, and then finds a percentage of the sum depending on what state you choose, and then it adds the percentage. This script worked kind of fine without the if..else statement, but now that I added it, it won't work. Please help. Script:
<!DOCTYPE html>
<html>
<head>
<title>Test!!!!!</title>
<style>
</style>
</head>
<body>
<h2> Price checker </h2>
<input id = "x" type = "number" placeholder = "Price 1" >
<br><br><br>
<input id = "y" type = "number" placeholder = "Price 2" >
<br><br><br>
<select id="s">
<option value="NJ">NJ</option>
<option value="NY">NY</option>
<option value="PA">PA</option>
<option value="FL">FL</option>
</select>
<br><br><br>
<button onclick = "theFunction()">Calculate price</button>
<p id = "d"></p>
<script>
function theFunction() {
var x = document.getElementById("x").value
var y = document.getElementById("y").value
var z = +x + +y
var v = document.getElementById("s").value
var percentToGet;
var percent;
var final;
if v == "NJ" {
var percentToGet = 6.625;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
} else if v == "NY" {
var percentToGet = 4;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
}else if v == "PA" {
var percentToGet = 2;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
} else if v == "FL" {
var percentToGet = 6;
var percent = (percentToGet / 100) * z;
var final = +percent + +z
}
document.getElementById("d").innerHTML = z + " " + final
}
</script>
</body>
</html>
Your if statement in the script tag ,is javascript code which is not having the parentheses.
It will be => if (v == "NJ") { }
Refer this MDN Web Docs to learn more if...else

Sharing random variables between functions

I'm trying to code a game and part of it has a combat system. I want the player to click a button as many times as they want to find an opponent, then to click the attack button when they find one they like and a timed event happens to slowly reveal the result.
The problems I'm coming against are:
- If the VAR are outside the functions, then you can only infiltrate once, but if it's inside the first function then the other ones can't use those values for the battle.
- The max_acres for victory comes across as a string so instead of 10+3=13, it becomes 103. How can I fix that?
Thank you very much for looking and I appreciate the help!
Javascript:
var titles = ["Peasant", "Knight"];
var first = ["Ada", "Adro", "Ama"];
var last = ["nija", "har", "nake"];
var random_name1 = titles[Math.floor(Math.random() * titles.length)] + ' ' + first[Math.floor(Math.random() * first.length)] + last[Math.floor(Math.random() * last.length)];
var random_acres1 = (max_acres * (Math.floor(Math.random() * (140 - 75)) + 75) / 100).toFixed(0);
var random_troops1 = (random_acres1 * (Math.floor(Math.random() * (1500 - 600)) + 600) / 100).toFixed(0);
var random_off1 = (random_troops1 * (Math.floor(Math.random() * (1200 - 400)) + 400) / 100).toFixed(0);
var combat_victory_acres1 = (random_acres1 * (((Math.random() * (35 - 11)) + 11) / 100)).toFixed(0);
var combat_defeat_acres1 = (random_acres1 * (Math.floor(Math.random() * (20 - 11)) + 11) / 100).toFixed(0);
var text_victory = 'You have been awarded with ';
var text_defeat = 'You have lost control of ';
var text_acres = ' acres.';
function infiltrate(){
var x = document.getElementById("Combat_table");
if (x.style.display === "none") {
x.style.display = "block";
}
document.getElementById('combat_army_strength').innerHTML = army_strength;
document.getElementById('combat_max_acres').innerHTML = max_acres;
document.getElementById('random_name1').innerHTML = random_name1;
document.getElementById('random_acres1').innerHTML = random_acres1;
document.getElementById('random_troops1').innerHTML = random_troops1;
document.getElementById('random_off1').innerHTML = random_off1;
};
function attack_random1(){
document.getElementById("attack_button1").style.display="none";
document.getElementById("infiltration").style.display="none";
var y = document.getElementById("Combat_Results");
if (y.style.display === "none") {
y.style.display = "block";
}
setTimeout(Combat_Text4, 5000)
var final_outcome1 = army_strength - random_off1;
if (final_outcome1 >= 0) {
setTimeout(Combat_Text_Victory1, 6000);
} else {
setTimeout(Combat_Text_Defeat1, 6000);
}
};
function Combat_Text4() {
document.getElementById("Combat_Results4").innerHTML = "The battle is over, a scout is dispatched to you with the results.";
}
function Combat_Text_Victory1() {
max_acres = max_acres + combat_victory_acres1;
var text_victory_1 = text_victory + combat_victory_acres1 + text_acres;
document.getElementById("Combat_Results5").innerHTML = "You achieved <b>Victory!</b>";
document.getElementById("Combat_Results6").innerHTML = text_victory_1;
document.getElementById('max_acres').innerHTML = max_acres;
document.getElementById('combat_max_acres').innerHTML = max_acres;
}
function Combat_Text_Defeat1() {
max_acres = max_acres - combat_defeat_acres1;
var text_defeat_1 = text_defeat + combat_defeat_acres1 + text_acres;
document.getElementById("Combat_Results5").innerHTML = "You have been <b>Defeated!</b>";
document.getElementById("Combat_Results6").innerHTML = text_defeat_1;
document.getElementById('max_acres').innerHTML = max_acres;
document.getElementById('combat_max_acres').innerHTML = max_acres;
}
HTML:
<div id="Combat" class="tabcontent">
Total Land: <span id="combat_max_acres">10</span><br>
Total Offense: <span id="combat_army_strength">0</span><p>
<button id="infiltration" onclick="infiltrate()">Infiltrate Kingdoms</button>
<div id="Combat_table" style="display: none">
<center><table>
<tr valign="center">
<th>Kingdom Name</th>
<th>Acres</th>
<th>Troop <br>Numbers</th>
<th>Total <br>Offense</th>
<th></th>
</tr>
<tr id="combat_row1">
<td><span id="random_name1"></span></td>
<td><span id="random_acres1"></span></td>
<td><span id="random_troops1"></span></td>
<td><span id="random_off1"></span></td>
<td><button onclick="attack_random1()" id="attack_button1">Attack!</button></td>
</tr>
</table>
</div>
<br>
<div id="Combat_Results" style="display: none">
<center><table><tr>
<td><center><span id="Combat_Results4"></span></td>
</tr><tr>
<td><center><span id="Combat_Results5"></span></td>
</tr><tr>
<td><center><span id="Combat_Results6"></span></td>
</tr>
</table>
</div>
The max_acres for victory comes across as a string so instead of 10+3=13, it becomes 103. How can I fix that?
Use Math.round instead of Number#toFixed, because for addition numerical values, you need both operands as number, not a string.
Use toFixed only for displaying a number.
For the other parts, I suggest to use an object with arrays for same items, like
{
name: [],
acres: [],
troops: [],
off: [],
victory_acres: [],
combat_defeat_acres: [],
// etc.
}

Button does nothing when pressed

I've been working on my own project for a little bit, and I'm currently working on adding another button in. Now I've set it up pretty similar to the other ones, but it isn't working when I press it. For my code, the firstx2, secondx2, and first building buttons all work fine, But when you try and click on the second building button, it doesn't do anything. I probably made a small typo or missed a line, but I can't seem to find it anywhere. To get to the second building button, you have to have already clicked on both multipliers and the first building. Thanks for your help!
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost x</button>
<button id="multiply2" onclick="secondx2()" style="display:none;">x2 Multiplier. Cost: 1000</button>
<button id="secondbuild" onlcick="build2()" style="display:none;">Building 2. Cost x</button>
<script>
var points = 10099;
var pointMulti = 1;
var buyupgrade = 0;
var b1cost = 200;
var b1count = 0;
var b2cost = 1000;
var b2count = 0;
var currentpoints = setInterval(pointupdate, 500);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + Math.round(points) + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti;
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
firstbuild.innerText = "Building 1. Cost " + b1cost;
var show2ndx2 = document.getElementById("secondx2");
multiply2.style.display = "inline";
}
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + Math.round(points) + " points!";
}
function build1() {
if (points >= b1cost) {
points -= b1cost;
b1count++;
b1cost *= 1.10;
document.getElementById("b1").innerHTML = "You have " + b1count + " of building 1!"
firstbuild.innerText = "Building 1. Cost " + Math.round(b1cost);
var build1add = setInterval(build1points, 1000);
var secondbuild = document.getElementById("secondbuild");
secondbuild.style.display = "inline";
secondbuild.innerText = "Building 2. Cost " + b2cost;
}
}
function build2() {
if (points >= b2cost) {
points -= b2cost;
b2count++;
b2cost *= 1.10;
document.getElementById("b2").innerHTML = "You have " + b2count + " of building 2!"
secondbuild.innerText = "Building 2. Cost " + Math.round(b2cost);
var build2add = setInterval(build2points, 1000);
}
}
function build1points() {
points += 1;
}
function build2points() {
points += 4;
}
function secondx2() {
if (buyupgrade == 1 && points >= 1000) {
pointMulti *= 2;
points -= 1000;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti;
multiply2.style.display = "none";
}
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
<p id="b1"></p>
<p id="b2"></p>
</body>
</html>
it should be onclick not onlcick in <button id="secondbuild" onlcick="build2()" style="display:none;">Building 2. Cost x</button>
<!DOCTYPE html>
<html>
<body>
<p>Click to get started!</p>
<button onclick="addPoints()">Add points</button>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost x</button>
<button id="multiply2" onclick="secondx2()" style="display:none;">x2 Multiplier. Cost: 1000</button>
<button id="secondbuild" onclick="build2()" style="display:none;">Building 2. Cost x</button>
<script>
var points = 10099;
var pointMulti = 1;
var buyupgrade = 0;
var b1cost = 200;
var b1count = 0;
var b2cost = 1000;
var b2count = 0;
var currentpoints = setInterval(pointupdate, 500);
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + Math.round(points) + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
}
}
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti;
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
firstbuild.innerText = "Building 1. Cost " + b1cost;
var show2ndx2 = document.getElementById("secondx2");
multiply2.style.display = "inline";
}
}
}
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + Math.round(points) + " points!";
}
function build1() {
if (points >= b1cost) {
points -= b1cost;
b1count++;
b1cost *= 1.10;
document.getElementById("b1").innerHTML = "You have " + b1count + " of building 1!"
firstbuild.innerText = "Building 1. Cost " + Math.round(b1cost);
var build1add = setInterval(build1points, 1000);
var secondbuild = document.getElementById("secondbuild");
secondbuild.style.display = "inline";
secondbuild.innerText = "Building 2. Cost " + b2cost;
}
}
function build2() {
if (points >= b2cost) {
points -= b2cost;
b2count++;
b2cost *= 1.10;
document.getElementById("b2").innerHTML = "You have " + b2count + " of building 2!"
secondbuild.innerText = "Building 2. Cost " + Math.round(b2cost);
var build2add = setInterval(build2points, 1000);
}
}
function build1points() {
points += 1;
}
function build2points() {
points += 4;
}
function secondx2() {
if (buyupgrade == 1 && points >= 1000) {
pointMulti *= 2;
points -= 1000;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti;
multiply2.style.display = "none";
}
}
</script>
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
<p id="b1"></p>
<p id="b2"></p>
</body>
</html>
I think you should check your button(secondbuild)
the keyword onclick is wrong
Spelling Mistake. onclick not oncilck.
<button id="secondbuild" onlcick="build2()" style="display:none;">Building 2. Cost x</button> <script>

The functions aren't cooperating :/

function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
document.getElementById("input").innerHTML = "<input id=>";
document.getElementById("check").innerHTML = "<button>Check</button>";
}
function myBunction() {
myFunction();
var b, text;
// Get the value of the input field with id="numb"
b = document.getElementById("input").value;
var D = document.getElementById("demoX").value;
var E = document.getElementById("demoY").value;
// If x is Not a Number or less than one or greater than 10
if (b == E + D) {
text = "Input is ok";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
}
<p>Click the button to display a random number between 1 and 10.</p>
<button onclick="myFunction()">Try it</button>
<br> <br>
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id=equal></span>
<span id=input></span>
<span onclick="myBunction()" id=check></span>
<p id="demo"></p>
The first function throws two random numbers and the second one should check if the input form person is correct but "document.getElementById("demoX").value" returns nothing ... I was trying check values with console.log but it returns like nothing is define.
I was just trying to merge two functions from w3schools but it took me so much time. :/
Your problem is four-fold. One:
document.getElementById("demoX").value
does not return anything. A <span> element has no value. It has an innerHTML, just what you used to set it.
Two:
if (b == E + D) {
E and D will be strings. The result of adding two strings is a combined string.
"4" + "3" is not "7", it is "43".
You want to convert them to numbers first. Among other things, an unary + can do that. Try:
b = +b;
D = +D;
E = +E;
if (b == E + D) {
Three: You want to reset the form after you read out all values, not before.
Four: What's all that business creating all those fixed input fields and buttons dynamically via innerHTML anyway? Just put them into the HTML directly and let them sit there.
So...
function reset() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("input").value = "";
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
}
function check() {
var b, D, E, text;
// Get the value of the input field with id="numb"
b = +document.getElementById("input").value;
D = +document.getElementById("demoX").innerHTML;
E = +document.getElementById("demoY").innerHTML;
if (b == E + D) {
text = "Input is ok";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
reset();
}
reset();
<p>Click the button to display a random number between 1 and 10.</p>
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id="equal"></span>
<input id="input">
<button onclick="check()">Check</button>
<p id="demo"></p>
Solved and nicer code.
Test
<script>
//=====|Generate the problem|=====//
function myGenerator() {
var x = Math.floor((Math.random() * 100) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 100) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
document.getElementById("numbs").innerHTML = "<input id=numb>";
document.getElementById("check").innerHTML = "<button>Check</button>";
}
//=====|Check the given solution|=====//
function myChecker() {
var a, text;
a = document.getElementById("numb").value;
var b = parseFloat(document.getElementById("demoX").textContent);
var c = parseFloat(document.getElementById("demoY").textContent);
//=====|Simple if|=====//
if (a == b + c) {
alert("Congratulation");
text = "Right";
} else {
alert("Maybe next time");
text = "Wrong";
}
document.getElementById("demo").innerHTML = text;
//=====|Just for control|=====//
console.log(a);
console.log(b);
console.log(c);
}
</script>
<h1>Click to start</h1>
<button onclick="myGenerator()">Try it</button>
<br>
<br>
<!--=====|Hidden Stuff|=====//-->
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id="equal"></span>
<span onclick="myChecker()" id=check></span>
<span id="numbs"></span>
<!--=====|Response|=====//-->
<p id="demo">

JavaScript and HTML Form 'Bank'

I want to be able to have a form that takes a 'deposit' or 'withdraw' and will add or subtract for a variable. Then, I would like to be able to put that variable in the webpage, and be able to keep it for a day or two. I do not know what is wrong with my code at this point.
<html>
<head>
<script language="JavaScript">
<!-- hide this script from old browsers
//Bank
var bank = 0;
var bank_name = "The Bank of Pacycephalosaurus";
var bank_interestPolicy = 0;
var bank_interestPolicy_interestAmount = 2;
var bank_ineterestPolicy_interest = function (amount) {
var interestGain = bank_contents_money / bank_interestPolicy_interestAmount;
var bank_contents_money = bank_contents_money + interestGain;
};
var bank_contents = 0;
var bank_contents_money = 0;
var bank_contents_items = "None";
var bank_withdrawAmount = "0";
var bank_depositAmount = "0";
var bank_withdraw = function (amount) {
//Check if there is money
if (bank_contents_money < amount) {
alert("Withdraw DENIED Insufficient Funds");
} else {
alert("Sufficient Funds ... Transfering Funds ...");
var transPlace = confirm("Transfer funds to " + wallet_name + "?");
if (transPlace === false) {
alert("Transfer Location Unknown :: 404 Not Found :: Please Try Again");
} else {
alert("Transfering Funds ... Transfer Succesful!");
form.bank_money.value = bank_contents_money - amount;
wallet_money = wallet_money + amount;
}
}
};
var bank_deposit = function (amount) {
//Check if there is money
if (wallet_money < amount) {
alert("Deposit DENIED Insufficient Funds");
} else {
alert("Sufficient Funds ... Transfering Funds ...");
var transPlace = confirm("Transfer funds to " + bank_name + "?");
if (transPlace === false) {
alert("Transfer Location Unknown :: 404 Not Found :: Please Try Again");
} else {
alert("Transfering Funds ... Transfer Succesful!");
alert("The Amount: " + amount);
form.bank_money.value = bank.contents_money + amount;
bank_contents_money = bank.contents_money + amount;
alert("The Amount: " + amount);
bank_opening(amount);
}
}
};
var bank_opening = function (money) {
alert("You have $" + bank_contents_money + " in your bank.");
$.cookie("bankMoney", money, {
expires: 1
});
alert($.cookie("example"));
};
var wallet = 0;
var wallet_name = "Wallet of You!";
var wallet_money = 0;
bank_opening();
// done hiding from old browsers -->
</script>
</head>
<body>
<form>
<h2>Bamk</h2>
Enter a number to withdraw or deposit:
<INPUT NAME="deposit" VALUE="0" MAXLENGTH="15" SIZE=15>
<p>
<INPUT NAME="depos" VALUE="Deposit" TYPE=BUTTON
onClick=bank_deposit(deposit.form)>
<p>
<p>
<INPUT NAME="withd" VALUE="Withdraw" TYPE=BUTTON
onClick=bank_withdraw(this.form)>
<p>
The amount in a bank is:
<INPUT NAME="bank_contents_money" READONLY SIZE=15>
</form>
</body>
</html>

Categories

Resources