JavaScript code not executed when I press "submit button" - javascript

I have a JavaScript code which calculates the total cost of accomodation, but whenever i run it it doesn't work.
I have tried debugging the code but I can't seem to find any problems.
Can you please help me fix this code.
This is JavaScript and the HTML is below it:
function calcStayCost(pricePerNight, numberOfNights) {
return pricePerNight * numberOfNights
}
function calcDiscount(numNights, standardCost) {
var dRate;
if (numberOfNights < 5) {
dRate = 0
} else {
if (numberOfNights >= 5 && numberOfNights <= 10) {
dRate = 0.03
} else {
dRate = 0.05
}
}
return dRate;
}
function calcAmount(cost, discount) {
return cost - discount;
}
function validateInput(validNumber) {
if (validNumber > 0) {
return true;
}
else {
return false;
}
}
function processQuote() {
var pricePerNight = document.getElementById('price').value;
pricePerNight = Number(pricePerNight);
var totalNights = document.getElementById('nights').value;
totalNights = Number(totalNights);
var validPrice = validateInput(pricePerNight);
var validNights = validateInput(totalNights);
if (validPrice == true && validNights == true) {
var standardCost = calcStayCost(pricePerNight, totalNights);
var standardCostOut = document.getElementById('price').innerHTML = "The standard cost of stay is: $" + standardCost;
var discountAmount = calcDiscount(totalNights, standardCost);
var totalAmountDue = calcAmount(standardCost, discountAmount);
var discountOut = document.getElementById('discount').innerHTML = "The total discount amount is: $" + discountAmount;
var totalDueOut = document.getElementById('amount').innerHTML = "The total amount due is: $" + totalAmountDue;
}
else {
if (validPrice == false) {
var priceErrorOut = document.getElementById('priceErrorMessage').innerHTML = "The price" + pricePerNight + "you entered is invalid, please enter a value greater than $0";
}
if (validNights == false) {
var nightsErrorOut = document.getElementById('nightsErrorMessage').innerHTML = "The number of nights you entered is invalid, please enter a value of 1 or more"
}
}
}
function init() {
var btn = document.getElementById('send');
btn.onclick = processQuote;
}
End of JavaScript Code. The following is the HTML script:
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="description" content="Quote calculator" />
<meta name="keywords" content="quote, calculator, javascript, html" />
<meta name="author" content="Mario Stavreski" />
<title>Testing output</title>
<script src="w4P1.js"></script>
</head>
<body>
<header>
</header>
<article>
<h2> Accomodation Quote </h2>
<form>
<label> Price Per Night: <input type="text" id="pricePerNight" /> </label>
<label> Number of Nights <input type="text" id="noNights" /> </label>
<button type="button" id="send"> Submit </button>
</form>
<p id="price"></p>
<p id="discount"></p>
<p id="amount"></p>
<p id="priceErrorMessage"></p>
<p id="nightsErrorMessage"></p>
</article>
<footer><p>Produced by Mario Stavreski</p></footer>
</body>
</html>

You need to either call init() to actually trigger the method so that the onSubmit handler gets bound to your button or alternatively, you can bind it within the HTML like so
<form onsubmit="processQuote()">
<label> Price Per Night: <input type="text" id="pricePerNight" /> </label>
<label> Number of Nights <input type="text" id="noNights" /> </label>
<button type="submit" id="send"> Submit </button>
</form>
Note I change the button type to submit so that it submits the form when clicked

Related

Display answer of 'Add and Subtract' buttons using javascript

So I am trying to practice javascript and so I'm trying to do a small javascript code in which a random number is generated whenver the page loads and then the user has the option of subtracting or adding 10 from that number. The user can also input any text in the textfield and the text there will be displayed with the answer. For ex: if the random number generated is 100 and the user choose the 'subtract 10' option and wrote 'Hello' in the text field, the output will be '90Hello'.
I did most of the code, but I can't figure out how to display the answer because it doesn't work for some reason. The random number is shown but the add and subtract buttons are not working. Can someone help with that?
The code till now is:
count = 0;
let y = Math.floor(Math.random() * 100) + 1;
y = document.getElementById("numb").innerHTML;
function subtractTen() {
var t1 = document.getElementById("te");
var n1 = document.getElementById("numb") * 10;
var subtract = Number(n1.value);
var ans = subtract + t1;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function addTen() {
var t2 = document.getElementById("te");
var n2 = document.getElementById("numb") / 10;
var add = Number(n2.value);
var ans = add + t2;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function reset() {
count = countN * 0;
var res = document.getElementById("numb");
res.innerHTML = count;
}
<html>
<head>
<title></title>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen();" value="sub" /> Subtract 10 </button>
<button onClick="addTen();" value="add" /> Add 10 </button>
<button onClick="reset();" value="res" /> Reset </button>
<br />
<input name="text" id="te" />
<span id="numb" id="answer"></span>
</body>
</html>
//script.js
const container = document.getElementById('answer');
let num = generateRandom(1, 200)
let inputText = '';
function changeText() {
inputText = document.getElementById('te').value
container.innerText = inputText + num;
}
function generateRandom(min, max) {
return Math.floor(Math.random() * (max-min) + min);
}
function subtractTen() {
num -= 10;
container.innerText = inputText+num;
}
function addTen() {
num += 10;
container.innerText = inputText+num;
}
function reset() {
num = generateRandom(1, 200);
container.innerText = num
inputText = '';
document.getElementById('te').value = ''
}
container.innerText = num;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script defer src="script.js"></script>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen()" value="sub" /> Subtract 10 </button>
<button onClick="addTen()" value="add" /> Add 10 </button>
<button onClick="reset()" value="res" /> Reset </button>
<br />
<input oninput="changeText()" name="text" id="te" />
<span id="answer"></span>
</body>
</html>

How do you call a function only once until victory conditions are met?

<!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>Higher Lower</title>
</head>
<body>
<h1>Higher - Lower</h1>
<!--maxNum Function-->
<!-- <p>Please enter a maximum number:</p>
<input type="text" id="maxNum" /><br /><br /> -->
<button onclick="userInput()">Input Maximum Number</button>
<p id="ranNum"></p>
<p id="validation"></p>
<!--higherLower Function-->
<p>Your Guess:</p>
<input type="text" onfocus="this.value=''" id="choice" /><br /><br />
<button onclick="higherLower()">Guess</button>
<p id="result"></p>
<p id="values"></p>
</body>
<script src="scripts.js"></script>
</html>
let userMax;
function userInput() {
userMax = prompt("Please enter a maximum number:");
while (userMax < 1 || isNaN(userMax)) {
alert("Maximum number cannot be negative, zero, or non-numbers");
userMax = userInput();
}
return userMax;
}
function isFloat(userMax) {
return Number(userMax) === n && n % 1 !== 0;
}
function higherLower(choice) {
// Declares random number variable
var randomNumber=Math.floor(Math.random() * userMax) + 1;
window.alert(randomNumber);
// Declares user guess variable
var guess=document.getElementById('choice').value;
// Declares random number variable
if(randomNumber==guess) {
document.getElementById("result").innerHTML = "You got it!";
}
else if(randomNumber>=guess) {
document.getElementById("result").innerHTML = "No, try a higher number.";
}
else if(randomNumber<=guess) {
document.getElementById("result").innerHTML = "No, try a lower number.";
}
}
I am creating a number guessing game based on the user inputting the maximum number. I was wondering how I could generate the random number only once until the user guesses correctly?
I messed around with creating another function and nesting functions however I could not get anything solid to work.
Currently, the button calls the main game function each time it is clicked and I do not want to add other buttons/inputs to solve this issue.
Place var randomNumber=Math.floor(Math.random() * userMax) + 1; outside of your function, and it should not be replaced when you call higherLower().
If the user guesses correctly, then set randomNumber to another Math.floor(Math.random() * userMax) + 1
So, your code should look like this:
let userMax;
let randomNumber;
function userInput() {
userMax = prompt("Please enter a maximum number:");
while (userMax < 1 || isNaN(userMax)) {
alert("Maximum number cannot be negative, zero, or non-numbers");
userMax = userInput();
}
randomNumber = Math.floor(Math.random() * Number(userMax)) + 1;
return userMax;
}
function isFloat(userMax) {
return Number(userMax) === n && n % 1 !== 0;
}
function higherLower(choice) {
// Declares random number variable
window.alert(randomNumber);
// Declares user guess variable
var guess=document.getElementById('choice').value;
// Declares random number variable
if(randomNumber==guess) {
document.getElementById("result").innerHTML = "You got it!";
randomNumber=Math.floor(Math.random() * Number(userMax)) + 1;
}
else if(randomNumber>=guess) {
document.getElementById("result").innerHTML = "No, try a higher number.";
}
else if(randomNumber<=guess) {
document.getElementById("result").innerHTML = "No, try a lower number.";
}
}
This happens because you are generating a random number in every call to higherLower function
so you have to declare to variable outside and set up a random number to it out side this function
let userMax;
let randomNumber;
function start() {
userMax = prompt("Please enter a maximum number:");
if (userMax < 1 || isNaN(userMax)) {
alert("Maximum number cannot be negative, zero, or non-numbers");
userMax = start();
}
randomNumber = Math.floor(Math.random() * Number(userMax)) + 1;
}
function higherLower() {
// Declares random number variable
window.alert(randomNumber);
// Declares user guess variable
var guess=document.getElementById('choice').value;
// Declares random number variable
if(randomNumber==guess) {
document.getElementById("result").innerHTML = "You got it!";
}
else if(randomNumber>=guess) {
document.getElementById("result").innerHTML = "No, try a higher number.";
}
else if(randomNumber<=guess) {
document.getElementById("result").innerHTML = "No, try a lower number.";
}
}
And you do not have to use while in while (userMax < 1 || isNaN(userMax))
you just can put a simple if statement,
<!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>Higher Lower</title>
</head>
<body>
<h1>Higher - Lower</h1>
<!--maxNum Function-->
<!-- <p>Please enter a maximum number:</p>
<input type="text" id="maxNum" /><br /><br /> -->
<button onclick="start()">Input Maximum Number</button>
<p id="ranNum"></p>
<p id="validation"></p>
<!--higherLower Function-->
<p>Your Guess:</p>
<input type="text" onfocus="this.value=''" id="choice" /><br /><br />
<button onclick="higherLower()">Guess</button>
<p id="result"></p>
<p id="values"></p>
</body>
<script src="scripts.js"></script>
</html>
And I changed the name of userInput function to start

Javascript textcontent is not displaying anything

I am trying to create the below game. The Javascript textcontent however is not displaying anything.
The Computer selects a random "secret" number between some min and max.
The Player is tasked with guessing the number. For each guess, the application informs the user whether their number is higher or lower than the "secret" number.
Extra challenges:
Limit the number of guesses the Player has.
Keep track/report which numbers have been guessed.
My code is as follows:
const submitguess = document.querySelector('.submitguess');
const inputno = document.querySelector('#secretno');
const resultmatch = document.querySelector('#resultmatch');
const highorlow = document.querySelector('#highorlow');
const guesslist = document.querySelector('#guesslist');
let randomNumber = Math.floor(Math.random() * 10) + 1;
let count = 1;
let resetButton;
function guessvalid() {
let input = Number(inputno.value);
//alert('I am at 0');
if (count === 1) {
guesslist.textContent = 'Last guesses:';
}
guesslist.textContent += input + ', ';
if (randomNumber === input) {
//alert('I am here 1');
resultmatch.textContent = 'Bazingaa!!! You got it absolutely right';
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else if (count === 5) {
resultmatch.textContent = 'Game Over !! Thanks for playing.';
//alert('I am here 2');
highorlow.textContent = '';
guesslist.textContent = '';
GameOver();
} else {
//alert('I am here 3');
resultmatch.textContent = 'Sorry the secret no and your guess do not match.Please try again !!';
if (randomNumber > input) {
//alert('I am here 4');
highorlow.textContent = 'Hint.The guess was lower than the secret no.';
} else if (randomNumber < input) {
//alert('I am here 5');
highorlow.textContent = 'Hint.The guess was higher than the secret no.';
}
}
count = count + 1;
input.value = '';
}
submitguess.addEventListener('click', guessvalid);
function GameOver() {
inputno.disabled = true;
submitguess.disabled = true;
resetButton = document.createElement('button');
resetButton.textContent = 'Lets play again';
document.body.appendChild(resetButton);
resetButton.addEventListener('click', reset);
}
function reset() {
count = 1;
const newDisplay = document.querySelectorAll('.display p');
for(let k = 0 ; k < newDisplay.length ; k++) {
newDisplay[k].textContent = '';
}
resetButton.parentNode.removeChild(resetButton);
inputno.disabled = false;
submitguess.disabled = false;
inputno.value = '';
randomNumber = Math.floor(Math.random() * 10) + 1;
}
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<title>Hi Low</title>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h3>Lets guess the secret number between 1 and 10</h3>
<h4>You have 5 chances to guess </h4>
</header>
<br/>
<br/>
<form class='form'>
<div class='secretno'>
<label for='secretno'>Please enter your guess for secret no (between 1 and 10):</label>
<input id='secretno' type='number' name='secretno' step='1' min='1' max='10' required>
<span class='validity'></span>
<input type='button' class='submitguess' value='submit'>
</div>
</form>
<br/>
<br/>
<div class='display'>
<p id='resultmatch'> </p>
<p id='highorlow'> </p>
<p id='guesslist'> </p>
</div>
Because I don't have enough contribution I have to write as an answer.
First is here
<input type='submit' class='submitguess'>
you should prevent the form to be executed and refresh so you have to add preventdefault. or simply change input submit to button type="button"
Second
const resetParas = document.querySelectorAll('.display p');
You should check this one. resetParas set but you check display length.

There's a simple logic error in my JS that I lack the knowledge to find

<!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.

undefined output from Income Tax Calculator. JavaScript

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;

Categories