this is an exercise from Murach's Javascript and Jquery book. An income tax calculator. The code is pretty self explanatory. The error: undefined is popping up where the value of the tax owed should be. commented out if statement outputted the same 'undefined' error. The documentation said, undefined usually is outputted when a variable isn't assigned or returned and i've done all that.
JS
"use strict";
var $ = function (id) {
return document.getElementById(id);
};
var income;
var taxOwed;
var calculateTax = function(income){
/*if (income > 0 && income < 9275){
//incomeTax = taxableIncome - 0;
//percentIT = incomeTax * (10/100);
taxOwed = (income - 0) * (10/100) + 0;
taxOwed = parseFloat(taxOwed);
taxOwed = taxOwed.toFixed(2); //the tax should be rounded two
return taxOwed;
}*/
if (income < 9275){
taxOwed = income - 0 * .10 + 0;
}else if(income > 9275){
taxOwed = ((income - 9275) * .15) + 927.50;
}
return taxOwed;
};
var processEntry = function(){
income = parseInt($("income").value); //users entry should be converted
if(isNaN(income)){
alert("Entry must be a number");
}else if (income <= 0){
alert("income must be greater than 0");
}else{
$("taxOwed").value = calculateTax(income);
}
};
window.onload = function () {
$("calculate").onclick = processEntry;
$("income").focus();
};
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ace</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>Income Tax Calculator</h1>
<label>Enter taxable income:</label>
<input type="text" id="income" /> <!--income is variable name for taxable income-->
<input type="button" value="Calculate" name="calculate" id="calculate" /><br><br>
<label>Income tax owed:</label>
<input type="text" id="taxOwed"><br> <!--tax is variable name for taxOwed*-->
<script src="calculate_tax.js"></script>
</body>
</html>
You probably aren't passing anything in. put a debugger statement after income and open your dev console, check if the variable actually has a value.
//use val() not value
income = parseInt($("income").val());
debugger;
Related
I am new to learning these languages, and everything looks syntactically correct. The issue I'm having is that the correct button will just keep click as correct rather or not the answer is correct or not. The tables are updating, but I'm not sure where the issue is. The if-else statement looks to be okay (I know I don't need the else if in there). If anyone could help me figure out what is wrong I would appreciate it.
window.onload = function() {
equations();
};
window.onload = equations;
var sum;
var correct = 0,
incorrect = 0;
function equations() {
var a, b, sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a + b, a - b, a / b, a * b];
signs = ['+', '-', '÷', 'x'];
//assign random opperation
let randoArr = Math.floor(Math.random() * solve.length)
sum = solve[randoArr];
showSign = signs[randoArr];
//show in html
document.getElementById('showMath').innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
console.log(sum);
return (sum)
};
// Function checks if user Input is correct and then adds tallies to the table.
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function confirmIfRight() {
var userInput = document.getElementById('userInput').value;
const correctEl = document.getElementById('correctCount');
const incorrectEl = document.getElementById('incorrectCount');
sum = equations();
if (userInput = sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput = '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById('userInput').value = "";
}
<body>
<!--Equations load when web page is loaded up. -->
<script>
window.onload = function() {
equations();
};
</script>
<h1> Welcome to Fast Math! </h1>
<p> A website for solving simple math problems. </p>
<!-- Math Stuff-->
<div id="showMath">
</div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput" />
<input type="button" id="submit" value="Enter" onclick="confirmIfRight()" onclick="document.getElementById('userInput').value = '' " />
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount"> 0 </td>
<td id="incorrectCount"> 0 </td>
</tr>
</table>
</body>
The main reason your code wasn't working is because you aren't using the equality operator (==), you are using the assignment operator (=) in your if..else statements. Fixing that alone should resolve the main problem in your question.
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput == '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
However, this presents another problem in your code immediately: you're comparing sum immediately after reassigning it in confirmIfRight(). A new equation will have been generated prior to the comparison. This means the value in sum will most likely not be correct considering the original equation presented and the answer given.
To resolve this, remove the sum = equations(); line just before the if..else statements:
//sum = equations();
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else if (userInput == '') {
incorrect++;
incorrect.textContent = incorrect;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
Additionally, I do agree that you can remove the else if section and this should capture all cases where the answer does not equal the expected result.
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
Testing a few times showed that this is all you need to have your code working. Run the code snippet below as an example:
window.onload = equations;
var sum;
var correct=0, incorrect=0;
function equations(){
var a,b,sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a+b , a-b ,a /b ,a *b ];
signs = ['+', '-','÷','x'];
//assign random opperation
let randoArr = Math.floor(Math.random()*solve.length)
sum=solve[randoArr];
showSign=signs[randoArr];
//show in html
document.getElementById('showMath').innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
console.log(sum);
return(sum)
};
// Function checks if user Input is correct and then adds tallies to the table.
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function confirmIfRight(){
var userInput = document.getElementById('userInput').value;
const correctEl = document.getElementById('correctCount');
const incorrectEl= document.getElementById('incorrectCount');
//sum = equations();
if (userInput == sum) {
correct++;
correctEl.textContent = correct;
equations();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
equations();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById('userInput').value = "";
}
<!--Equations load when web page is loaded up. -->
<script>
window.onload = function(){
equations();
};
</script>
<h1> Welcome to Fast Math! </h1>
<p> A website for solving simple math problems. </p>
<!-- Math Stuff-->
<div id="showMath">
</div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput"/>
<input type="button" id ="submit" value="Enter"onclick="confirmIfRight()" onclick=
"document.getElementById('userInput').value = '' "/>
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount"> 0 </td>
<td id="incorrectCount"> 0 </td>
</tr>
</table>
There were a few mistakes that you did. The main issue was that you were generating a new equation and sum value every time you call equations function.
So I've saved the value in a new hidden input that is visually hidden from the user. And then compare it to the user input value. There is a plus sign in front of some methods and it is to convert the value to a number. Also, I allowed myself to make a few code naming changes so the code can feel better. Also, you can remove the return statement in the equation method since it has no reason to be there anymore.
let correct = 0,
incorrect = 0;
function generateEquation() {
var a, b, sum;
//assign random values to a,b
a = Math.floor(Math.random() * 10) + 1;
b = Math.floor(Math.random() * 10) + 1;
//array that holds values, MUST BE MUTUABLE
solve = [a + b, a - b, a / b, a * b];
signs = ["+", "-", "÷", "x"];
//assign random opperation
let randoArr = Math.floor(Math.random() * solve.length);
sum = solve[randoArr];
showSign = signs[randoArr];
//show in html
document.getElementById("showMath").innerHTML = a + showSign + b;
//This will be used to reassign the value to global variable
window.sum = sum;
document.getElementById("hiddenInput").value = sum;
return sum;
}
// The tables values are held in correct and incorrect and incremented based on the conditional statement.
function isCorrect() {
let userInput = +document.getElementById("userInput").value;
const correctEl = document.getElementById("correctCount");
const incorrectEl = document.getElementById("incorrectCount");
if (userInput === +document.getElementById("hiddenInput").value) {
correct++;
correctEl.textContent = correct;
generateEquation();
} else if (userInput == "") {
incorrect++;
incorrect.textContent = incorrect;
generateEquation();
} else {
incorrect++;
incorrectEl.textContent = incorrect;
generateEquation();
}
clearTextBox();
}
//This function is used to clear the textbox
function clearTextBox() {
document.getElementById("userInput").value = "";
}
generateEquation();
<!DOCTYPE html>
<html lang="eng">
<head>
<link rel="stylesheet" href="fastmath_style.css" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial scale = 1" ; />
<title>Fast Math</title>
</head>
<body>
<h1>Welcome to Fast Math!</h1>
<p>A website for solving simple math problems.</p>
<!-- Math Stuff-->
<div id="showMath"></div>
<!-- ANSWERS GO HERE -->
<form>
<input type="input" id="userInput" />
<input type="hidden" id="hiddenInput" />
<input
type="button"
id="submit"
value="Enter"
onclick="isCorrect()"
onclick="document.getElementById('userInput').value = '' "
/>
</form>
<!-- Score tally-->
<table>
<tr>
<td><b>Correct</b></td>
<td><b>Incorrect</b></td>
</tr>
<tr>
<td id="correctCount">0</td>
<td id="incorrectCount">0</td>
</tr>
</table>
<script src="./app.js"></script>
</body>
</html>
I'm very new to JavaScript so forgive me if the code is wrong. I have a problem getting a value from the user when the value is a number or letter.
If it is a number the function should execute, but if it is not a number it should display an alert telling the user to input a valid number.
Well, my application displays the alert when the user entry is both a letter and/or a number. Any help would be greatly appreciated.
I have tried using an if statement which will be shown in the code below under the Generate click function.
Edited to include HTML.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Password Generator</title>
<link rel="stylesheet" href="password.css">
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="password.js"></script>
</head>
<body>
<main>
<h1>Password Generator</h1>
<h2>Generate a strong password</h2>
<label for="num">Number of characters:</label>
<input type="text" id="num"><br>
<label for="password">Password:</label>
<input type="text" id="password" disabled><br>
<label> </label>
<input type="button" id="generate" value="Get Password">
<input type="button" id="clear" value="Clear"><br>
</main>
</body>
</html>
"use strict";
$(document).ready(function() {
var getRandomNumber = function(max) {
for (var x = 0; x < length; x++) {
var random;
if (!isNaN(max)) {
random = Math.random(); //value >= 0.0 and < 1.0
random = Math.floor(random * max); //value is an integer between 0 and max - 1
random = random + 1; //value is an integer between 1 and max
}
}
return random;
};
$("#generate").click(function() {
$("#password").val(""); // clear previous entry
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_-+!#";
var num;
if (num >= 0 && num <= 100) {
//If the user entry is valid, the function will execute and return password
return num;
//If user entry isn't a valid number, display alert
} else if (isNaN(num)) {
alert(" Please enter a valid number ");
}
}); // end click()
$("#clear").click(function() {
$("#num").val("");
$("#password").val("");
$("#num").focus();
}); // end click()
// set focus on initial load
$("#num").focus();
}); // end ready()
Please provide html part.
and when you click #generate, you didn't define the value of num variable.
Change this line and try again
var num= $("#num").val();
You should get the user input to a variable and validate that
var num = $("#password").val(""); // clear previous entry
if (isNaN(num)) {
return alert(" Please enter a valid number ");
}
else {
if (num >= 0 && num <= 100) {
return num;
else
// ..... return another error message here
}
<!DOCTYPE html>
<html>
<head>
<title>
Unit 2 Graded Exercise 1
</title>
</head>
<body>
<header>
<h1>Unit 2 Graded Exercise 1</h1>
<br/>
</header>
<form>
<fieldset>
<label for="price" id="label">Purchase Price</label>
<input type="text" id="partPrice" />
<button type="button" id="button">Calculate Shipping and Handling</button>
</fieldset>
</form>
</body>
<script>
var partPrice = document.getElementById("partPrice").value;
var totalPrice;
function calcTotal() {
if (partPrice <= 25) {
var totalPrice = partPrice + 1.5; //price + sh
} else if (partPrice > 25) {
var totalPrice = (partPrice * 0.10) + partPrice; //10% of price as sh + price
}
alert("Shipping and Handling is $" + totalPrice);
}
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", calcTotal, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", calcTotal);
}
</script>
</html>
So my goal is to show interest + $1.50 for a total cost below or equal to $25 and 10% interest of a total cost above $25. My problem is that the "partPrice", which is the price that the user enters, is not being received. I've looked up quite a bit about this and I've seen people go around by creating multiple variables to pick up certain values but I have yet to understand why. I would really like an explanation because, going through this code, it all looks logically correct. I'm really lost as to where I should be changing my syntax.
Update your code to following
Move the get value code inside the function
Convert the value which is a string to a number
function calcTotal() {
var partPrice = parseFloat(document.getElementById("partPrice").value);
...
}
Just get data inside function. also remove variable declaration in if statement
<html>
<head>
<title>
Unit 2 Graded Exercise 1
</title>
</head>
<body>
<header>
<h1>Unit 2 Graded Exercise 1</h1>
<br/>
</header>
<form>
<fieldset>
<label for="price" id="label">Purchase Price</label>
<input type="text" id="partPrice" />
<button type="button" id="button">Calculate Shipping and Handling</button>
</fieldset>
</form>
</body>
<script>
var partPrice,
totalPrice;
function calcTotal() {
partPrice = document.getElementById("partPrice").value;
if (partPrice <= 25) {
totalPrice = partPrice + 1.5; //price + sh
} else if (partPrice > 25) {
totalPrice = (partPrice * 0.10) + partPrice; //10% of price as sh + price
}
alert("Shipping and Handling is $" + totalPrice);
}
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", calcTotal, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", calcTotal);
}
</script>
</html>
var partPrice = document.getElementById("partPrice").value;
This line is executed once when the script is loaded, so partPrice will be an empty string. It doesn't get reevaluated automatically when you write anything in input, so you'll have to call document.getElementById("partPrice").value again in calcTotal to fetch the current value of partPrice.
I am writing a code that checks the user input and gives the result according to it. But the twist here is that the string can also contain the word 'dozen', which just means twelve. The thing will be cleared after looking at the following code:
HTML:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>iRock</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<form>
<label for="numDonut">Enter how many donuts you want: </label>
<input type="text" id="numDonut">
<div id="totalDonuts"></div>
<div id="submit" onclick="callDonut();">SUBMIT</div>
</form>
<script type="text/javascript" src="javascript.js"></script>
</body>
</html>
JS:
//Get string number of donuts entered
var numDonutString = document.getElementById('numDonut').value;
function getTotalDonuts(donutString){
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if(donutString.indexOf('dozen') != -1)
finalDonuts = initialDonutCount * 12;
else
finalDonuts = initialDonutCount;
return finalDonuts;
}
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(numDonutString);
}
Now here is the problem : No matter what input I give, even if it doesn't contain the word 'dozen', the function returns NaN, which is not making sense.
What can be the problem?
You need to change the function callDonut like :
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(document.getElementById('numDonut').value);
}
The problem: you don't reassign the new value of your input into the variable numDonutString
The problem you are having is you have tried to pre define your var numDonutString = document.getElementById('numDonut').value; however what this does is takes a copy of the value and it will never update that value.
So what you need to do is get the new value each time you click the SUBMIT button.
jsFiddle : https://jsfiddle.net/CanvasCode/xue6sbz2/
function getTotalDonuts(donutString){
alert(donutString);
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if(donutString.indexOf('dozen') != -1)
finalDonuts = initialDonutCount * 12;
else
finalDonuts = initialDonutCount;
return finalDonuts;
}
function callDonut(){
document.getElementById('totalDonuts').textContent = getTotalDonuts(document.getElementById('numDonut').value);
}
The problem is in the callDonut function and the text box value you are getting is only at the document load, so the value is always NaN.
window.getTotalDonuts = function(donutString) {
var initialDonutCount = parseInt(donutString);
var finalDonuts = 0;
if (donutString.indexOf('dozen') != -1) {
finalDonuts = initialDonutCount * 12;
} else {
finalDonuts = initialDonutCount;
}
return finalDonuts || 0;
}
window.callDonut = function() {
//Get string number of donuts entered
var numDonutString = document.getElementById('numDonut').value;
document.getElementById('totalDonuts').textContent = getTotalDonuts(numDonutString);
}
<form>
<label for="numDonut">Enter how many donuts you want:</label>
<input type="text" id="numDonut">
<div id="totalDonuts"></div>
<div id="submit" onclick="callDonut();">SUBMIT</div>
</form>
</body>
[DEMO][1]
So i am creating a simple dice game which you enter the guess of the dice roll and amount you wish to bet. I cant seem to figure out how i can get my balance to change when a user enters a number.
My code:
//declaring global variables
var diceroll = 0;
var balance = 1000;
var stake = 0;
var guess = 0;
while (balance <= 0) {
var guess = document.getElementById("guess").nodeValue;
var stake = document.getElementById("stake").nodeValue;
var diceroll = roll();
if (guess === diceroll) {
balance = balance + (stake * 5);
} else {
balance = balance - stake;
}
}
//Rolling the dice
function roll() {
"use strict";
diceroll = Math.floor(Math.random() * 6 + 1);
alert(diceroll);
}
//Display balance
document.getElementById("balance").innerHTML = balance;
<!DOCTYPE html>
<html>
<head>
<title>Dice-Game: GL HF</title>
</head>
<body>
<p id="balance"></p>
<form action="#">
Enter guess:
<input type="text" id="guess">
<br>Enter stake:
<input type="number" id="stake" name="stake">
<br>
<input type="button" name="play" onclick="roll()" value="PLAY!">
<br>
</form>
<script src="Dice.js" type="text/javascript"></script>
</body>
</html>
A few things:
The way I looked at it, your while loop wasn't doing anything. The whole balance calculation wasn't even part of your roll function. I removed it altogether.
You were using .nodeValue to get your guess and stake input values, which is deprecated. It should just be .value. Those two variables were returning null.
Your balance update wasn't being called with your function either, so it wouldn't have updated on the page even if the balance was actually updating.
Your declaration of global variables was a bit redundant and unnecessary.
//declaring global variables
var balance = 1000;
//Rolling the dice
function roll() {
var guess = document.getElementById("guess").value;
var stake = document.getElementById("stake").value;
"use strict";
var diceroll = Math.floor(Math.random() * 6 + 1);
alert(diceroll);
if(guess == diceroll) {
balance = balance + (stake * 5);
} else {
balance = balance - stake;
}
//Update display balance
document.getElementById("balance").innerHTML = balance;
}
//Initial display balance
document.getElementById("balance").innerHTML = balance;
Put
//Display balance
document.getElementById("balance").innerHTML = balance;
inside of the loop.
I also don't think your while condition is correct..
Try this,
balance = parseInt(balance) - parseInt(stake);