My problem is that for some reason the average of the grade does not run through the switch and i believe goes straight to default. How can i fix this little problem. must be a switch statement!
My input for grades is 76,99,85,88,83.
My guess is because my average is a 86.2? so like the decimal? I have tried to add a .0 at the end like i did for my if/ifelse and that seem to work.
<head>
<style>
hr {
background-color: black;
margin: 2px auto;
width: 100%;
height: 2px;
}
.container{
width: 500px;
padding: 15px;
background-color: #D3D3D3;
box-shadow: 10px 10px 5px 0px #8c878c;
}
body {
background-color: #EEE8AA;
}
form { display: table; }
p { display: table-row; }
label { display: table-cell; }
input { display: table-cell; }
</style>
</head>
<body>
<form name="gradecal">
<div class="container">
<p>
<label for="a">First Name: </label>
<input type="text" name="fname"/>
</p>
<p>
<label for="a">Last Name: </label>
<input type="text" name="lname"/>
</p>
<p>
<label for="a">Grade #1: </label>
<input type="text" name="grd1"/>
</p>
<p>
<label for="a">Grade #2: </label>
<input type="text" name="grd2"/>
</p>
<p>
<label for="a">Grade #3: </label>
<input type="text" name="grd3"/>
</p>
<p>
<label for="a">Grade #4: </label>
<input type="text" name="grd4"/>
</p>
<p>
<label for="a">Grade #5: </label>
<input type="text" name="grd5"/>
</p>
<p>
<input type="button" value="Submit" onclick="getGrades();" />
</p>
</div>
</form>
<script>
function getGrades(){
// initialize variables
var fname = 0, lname = 0, grade1 = 0, grade2 = 0, grade3 = 0, grade4 = 0, grade5 = 0, average = 0;
// assigning varables to textbox value
firnam = String(document.gradecal.fname.value);
lasnam = String(document.gradecal.lname.value);
grade1 = Number(document.gradecal.grd1.value);
grade2 = Number(document.gradecal.grd2.value);
grade3 = Number(document.gradecal.grd3.value);
grade4 = Number(document.gradecal.grd4.value);
grade5 = Number(document.gradecal.grd5.value);
// Calculate average
average = (grade1+ grade2+ grade3+ grade4+ grade5) / 5;
// if else to determine what grade falls into percentage wise
var perc = 0;
if (average >= 90 && average <=100){
perc = "100-99.9 %";
document.write(perc);
}
else if (average >= 80 && average <=89.9){
perc = "80-89.9 %";
document.write(perc);
}
else if (average >= 70 && average <=79.9){
perc = "70-79.9 %";
document.write(perc);
}
else if (average >= 60 && average <=69.9){
perc = "60-69.9 %";
document.write(perc);
}
else {
perc = "59.9 % or less";
document.write(perc);
}
// switch to determine the letter grade
var letter = 0;
switch (true){
case (average >= 90 && average <= 100):
letter = "A";
document.write(letter);
break;
case (average >= 80 && average <= 89.9):
letter = "B";
document.write(letter);
break;
case (average >= 70 && average <= 79.9):
letter = "C";
document.write(letter);
break;
case (average >= 60 && average <= 69.9):
letter = "D";
document.write(letter);
break;
default:
letter = "F";
document.write(letter);
break;
}
// display when submit is clicked
document.write('<p>First Name: ' + firnam.toUpperCase());
document.write('<br>Last Name: ' + lasnam.toLowerCase());
document.write('<br>Grade #1: ' + grade1);
document.write('<br>Grade #2: ' + grade2);
document.write('<br>Grade #3: ' + grade3);
document.write('<br>Grade #4: ' + grade4);
document.write('<br>Grade #5: ' + grade5);
document.write('<br>Semester Average: ' + average);
document.write('<hr>Based on your semester average, your grade falls between: ' + perc );
document.write('<br>You have earned a(n): ' + letter + '</p>');
}
</script>
</body>
</html>
expected result is "You have earned a(n): B" the result i am getting is "You have earned a(n): F".(corrected)
Also the perc and letter display in the first line when outputted, how can i only display it once??
The problem is the grade variables are undefined and get typecasted to 0
so the average is always 0, hence the default(else) will be set even if you write an if...else
update the code like below;
if(average >= 90.0)
letter = "A";
else if(average >= 80.0)
letter = "B";
else if(average >= 70.0)
letter = "C";
else if(average >= 60.0)
letter = "D";
else
letter = "F";
document.write('<br>You have earned a(n): ' + letter);
Update
The problem now is that unless the average is "exactly" 90,80,70 or 60, it will always be the "default" and give you F!
Update
Find the solution: https://jsfiddle.net/ur2nvxg4/2/
Again, if you have to use switch ranges, you must have switch(true) and case average >= value in the code for perc I see a potential error when the value is 89.99% from the code. it has also been modified
Some things could help us:
Why don't you console.log the average, and the typeof average?
There may be 2 issues going on here:
1) The grade variables are not getting the value from each of your inputs.
If this is the case, why don't you assign an ID to each input, since they represent a distinct value for each grade.
(If the inputs are dynamically created, you can create an ID for each of them associated with their index).
Lets say that we have :
<label for="a">Grade #1: </label>
<input type="text" name="grd1" id="grade1/>
Now we can get the value by doing:
const grade1 = document.querySelector("#grade1").value;
console.log the value of grade1 to make sure you're getting something back.
Also, you have to convert it to a number, as I believe the value is stored as a string.
2) Type mismatch
If you are getting back correct values for grade, try and console log the typeof each grade, and the average.
What could end up happening is that the average is actually a string, because the grades are treated as a string.
Related
I'm having trouble with my JS form. So I'm creating a change calculator which takes in two input values - the price and cash. When I explicity put in the actual values inside JS code (like the ones I commented out after confirmValues()), it works just fine. But when I put it in the actual input box, it doesn't give work anymore. Is there something weird with my HTML or JS? Thanks!
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title> Change calculator</title>
</head>
<body>
<form>
How much does the item cost? <input type="number" id="price" name ="price"/>
<br/> <br/>
How much cash do you have? <input type="number" id="cash" name="cash"/><br/> <br/>
<input type="button" value="Enter" onclick="confirmItems();"/>
</form>
<p id="confirmation"></p>
<p id ="change"></p>
</body>
var itemCost = document.getElementById("price");
var cash = document.getElementById("cash");
var confirmation = document.getElementById("confirmation");
function confirmItems() {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.value + " and you have $" + cash.value + " to pay for it.";
createConfirmationBtn();
}
function createConfirmationBtn() {
let confirmationBtn = document.createElement("BUTTON");
const confirmationBtnText = document.createTextNode("Confirm");
confirmationBtn.appendChild(confirmationBtnText);
confirmation.appendChild(confirmationBtn);
confirmationBtn.onclick = function() {
confirmValues();
}
}
let changeEl = document.getElementById("change");
function confirmValues() {
if (parseFloat(cash.value) < parseFloat(itemCost.value)) {
changeEl.innerHTML = "Not enough cash";
} else if (parseFloat(cash.value) == parseFloat(itemCost.value)) {
changeEl.innerHTML = "Your change is $0.";
} else {
calculateChange();
}
}
// cash.value = 500;
// itemCost.value = 33.44;
let remainder = parseFloat(cash.value) - parseFloat(itemCost.value);
let finalOutput = new Array();
function calculateChange() {
while (remainder > 0) {
if (remainder >= 100) {
findChange(100.00);
} else if (remainder >= 50.00) {
findChange(50.00);
} else if (remainder >= 20.00) {
findChange(20.00);
} else if (remainder >= 10.00) {
findChange(10.00);
} else if(remainder >= 5.00) {
findChange(5.00);
} else if (remainder >= 1.00) {
findChange(1.00);
} else if (remainder >= 0.25) {
findChange(0.25);
} else if (remainder >= 0.10) {
findChange(0.10);
} else if (remainder >= 0.05) {
findChange(0.05);
} else {
findChange(0.01);
}
}
changeEl.innerHTML = finalOutput;
}
function findChange(value) {
//Step 1. Get number of dollar for each type of dollar
let dValue = parseInt(remainder / value);
// Step 2. Storing numDValue in an array
finalOutput.push("[$" + value + " x" + dValue+"]");
remainder = parseFloat(remainder - (value * dValue));
remainder = parseFloat(remainder.toFixed(2));
}
You need to have the vars inside the functions that need them or they will not pick up what the user enters
You can show and hide the confirm button
DRY, Don't Repeat Yourself
function confirmValues() {
let itemCost = document.getElementById("price").value;
let cash = document.getElementById("cash").value;
const confirmation = document.getElementById("confirmation");
const changeEl = document.getElementById("change");
const confirm = document.getElementById("confirm");
cash = isNaN(cash) || cash === "" ? 0 : +cash; // test valid input
itemCost = isNaN(itemCost) || itemCost === "" ? 0 : +itemCost;
if (cash < itemCost) {
changeEl.innerHTML = "Not enough cash";
} else {
confirmation.innerHTML = "Your total purchase costs $" + itemCost.toFixed(2) + " and you have $" + cash.toFixed(2) + " to pay for it.";
changeEl.innerHTML = "Your change is $" + (cash - itemCost).toFixed(2);
confirm.classList.remove("hide");
}
}
.hide {
display: none;
}
<title> Change calculator</title>
<form>
How much does the item cost? <input type="number" id="price" name="price" />
<br/> <br/> How much cash do you have? <input type="number" id="cash" name="cash" /><br/> <br/>
<input type="button" value="Enter" onclick="confirmValues();" />
<input type="button" id="confirm" class="hide" value="Confirm" onclick="alert('Confirmed!')" />
</form>
<p id="confirmation"></p>
<p id="change"></p>
I'd like to ask on how to add label, input, and br in for loop please. I'm trying to create an application to calculate score/GPA with for loop. Basically, if I enter 4 then 4 boxes of test scores will show up for me to enter (the default value is 150) - and the maximum I can go is 5.
I'm having problem putting label, input, and br in the for loop - the code is fine and it ran, but you obviously see that I'm not using label, input, and br tags.
How may I add these in please?
For example, if I enter 3 in the number of exams, then setupInputBox() will generate three label, three input and three br elements.
I attached my codes below.
Thank you so much!
// define a function so that in js code, $ can be used to replace document.getElementById
var $ = function(id) {
return document.getElementById(id);
};
var numInputs = 1; //default setting, showing one test score input box
//define setupInputBox function to add more test score inputs boxes
var setupInputBox = function() {
$('testInputs').innerHTML = "";
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
numInputs = $('numscores').value;
numInputs = parseInt(numInputs);
// convert inputs into integer numerical value
//step-1.1: Add a condition in if() statement
//if user input for number of test scores is valid and in the range 1 to 5
if (Number.isInteger(numInputs) && numInputs >= 1 && numInputs <= 5) {
var mainDiv = document.getElementById("testInputs");
for (var i = 0; i < numInputs; i++) {
//Step-1.2.1: create new <label>, <input>, and <br> elements (use createElement() method)
var lbl = document.createElement('label');
var inp = document.createElement("input");
var br = document.createElement("br");
//Step-1.2.2: create text content node for each new <label> element ( use createTextNode() method )
lbl.append(document.createTextNode("Test-" + (i + 1)));
//Step-1.3.1: add for attribute to each new <label> element ( use setAttribute() method)
lbl.setAttribute("for", "score" + (i + 1));
//Step-1.3.2: add id, type, and value attributes to new <input> elements ( use setAttribute() method)
inp.setAttribute("id", "score" + (i + 1));
inp.setAttribute("value", "150");
inp.setAttribute("type", "number");
//Step-1.4: append each new <label>, <input>, and <br> elements to the <div> element with id=”testInputs”.
mainDiv.append(lbl, inp, br);
}
}
};
//whenever user changes selection on number of test scores to consider, setupInputBox function will be executed again
$('numscores').oninput = setupInputBox;
//define processEntries function to get user inputted test scores, do input validation, and caculate total and average points and
//determine the final letter grade. Display all results on web page.
var processEntries = function() {
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
var score = []; //define an array to hold test scores
var message = ""; //define a variable for containing and displaying error message
var totalscore = 0,
avgScore, finalScore;
var isValid = true;
for (var i = 0; i < numInputs; i++) //
{
$("score" + (i + 1)).className = "";
//step 2.1: add js code to read in each user inputted test score(s) from input test score boxes on the web page.
var test = document.getElementById("score" + (i + 1));
var testScore = parseFloat(test.value);
//step 2.2: add js code to validate each test score to make sure all inputted test scores are numerical values
//between 0 and 150 (i.e., no less than 0 and no greater than 150 points).
if (!Number.isNaN(testScore) && testScore >= 0 && testScore <= 150) {
//if a test score is valid, add that test score to the score array.
score.push(testScore);
} else {
isValid = false;
//if a test score is invalid, generate error message, and add that error messge to message string.
message += "Test-" + (i + 1) + " score input is invalid. Should be a number between 0 and 150.\n"
test.setAttribute("class", "error");
}
}
console.log(score); //print out score array in console
console.log(message); //print out message string in console
if (isValid) {
//step2.3: add js so that when all inputted test scores are valid, compute total points, average points (with zero decimal place), and
//final letter grade, and display them in the input boxes in the <div> element with id=’result’ on the web page.
for (var j = 0; j < numInputs; j++) {
totalscore += score[j];
}
totalscore = totalscore.toFixed(1);
avgScore = totalscore / numInputs;
avgScore = avgScore.toFixed(1);
var scoreTotal = document.getElementById('scoreTotal');
scoreTotal.value = totalscore.toString();
var scoreAvg = document.getElementById('scoreAvg');
scoreAvg.value = avgScore.toString();
avgScore = parseFloat(avgScore);
if (avgScore <= 150 && avgScore >= 120)
finalScore = "A";
else if (avgScore < 120 && avgScore >= 100)
finalScore = "B";
else if (avgScore < 100 && avgScore >= 80)
finalScore = "C";
else if (avgScore < 80 && avgScore >= 60)
finalScore = "D";
else if (avgScore < 60)
finalScore = "F";
var scoreFinal = document.getElementById("scoreFinal")
scoreFinal.value = finalScore
} else {
//If not all inputted test scores are valid, then create an alert box to display an error message
alert(message);
}
}; //end of processEntries function
//each time when calculate button is clicked, inputted test scores will be evaluated and
$("calculate").onclick = function() {
if (numInputs > 0 && numInputs < 6)
processEntries();
};
$("numscores").focus();
#import url(http://fonts.googleapis.com/css?family=Wellfleet);
body {
font-family: 'Wellfleet', Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 60%;
min-width: 600px;
border: 3px solid blue;
padding: 0 1em .5em;
}
h1 {
color: blue;
margin: .5em 0;
}
#teacher {
float: right;
margin: 0px 30px 0px 0px;
}
label {
float: left;
width: 10em;
text-align: right;
margin-bottom: .5em;
}
input {
width: 5em;
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: yellow;
}
#s1 {
display: inline-block;
}
#s1 input {
vertical-align: center;
float: left;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Score App</title>
<link rel="stylesheet" href="score.css">
</head>
<body>
<main>
<h2>The Test Scores App</h2>
<img src="teacher.png" id="teacher" alt="teacher" width="177" height="277">
<div id="s1">
<label for="numscores">How many tests you want to consider?</label>
<input type='number' id='numscores' min='1' max='10' value='1'>
</div>
<div id="testInputs">
<label for="score1">Test-1:</label>
<input type='number' id='score1' value='150' /><br>
</div>
<div id='result'>
<label for="scoreTotal">Total Points:</label>
<input type="number" id="scoreTotal" disabled><br>
<label for="scoreAvg">Avg Grade:</label>
<input type="number" id="scoreAvg" disabled><br>
<label for="scoreFinal">Final Letter Grade:</label>
<input type="text" id="scoreFinal" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
</div>
</main>
<script src="testScoreV2.js">
</script>
</body>
</html>
Use a template literal and you can make this a lot simpler
// define a function so that in js code, $ can be used to replace document.getElementById
var $ = function(id) {
return document.getElementById(id);
};
var numInputs = 1; //default setting, showing one test score input box
//define setupInputBox function to add more test score inputs boxes
var setupInputBox = function() {
$('testInputs').innerHTML = "";
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
//string to hold our new html
let newHTML = "";
numInputs = $('numscores').value;
numInputs = parseInt(numInputs);
// convert inputs into integer numerical value
//step-1.1: Add a condition in if() statement
//if user input for number of test scores is valid and in the range 1 to 5
if (Number.isInteger(numInputs) && numInputs >= 1 && numInputs <= 5) {
var mainDiv = document.getElementById("testInputs");
for (var i = 0; i < numInputs; i++) {
//Create new html using template literal
newHTML += `<label for='score${i+1}'>Test - ${i+1}</label><input type='number' value='150' id='score${i+1}'><br>`;
}
//Update the div
mainDiv.innerHTML += newHTML;
}
};
//whenever user changes selection on number of test scores to consider, setupInputBox function will be executed again
$('numscores').oninput = setupInputBox;
//define processEntries function to get user inputted test scores, do input validation, and caculate total and average points and
//determine the final letter grade. Display all results on web page.
var processEntries = function() {
$('scoreTotal').value = "";
$('scoreAvg').value = "";
$('scoreFinal').value = "";
var score = []; //define an array to hold test scores
var message = ""; //define a variable for containing and displaying error message
var totalscore = 0,
avgScore, finalScore;
var isValid = true;
for (var i = 0; i < numInputs; i++) //
{
$("score" + (i + 1)).className = "";
//step 2.1: add js code to read in each user inputted test score(s) from input test score boxes on the web page.
var test = document.getElementById("score" + (i + 1));
var testScore = parseFloat(test.value);
//step 2.2: add js code to validate each test score to make sure all inputted test scores are numerical values
//between 0 and 150 (i.e., no less than 0 and no greater than 150 points).
if (!Number.isNaN(testScore) && testScore >= 0 && testScore <= 150) {
//if a test score is valid, add that test score to the score array.
score.push(testScore);
} else {
isValid = false;
//if a test score is invalid, generate error message, and add that error messge to message string.
message += "Test-" + (i + 1) + " score input is invalid. Should be a number between 0 and 150.\n"
test.setAttribute("class", "error");
}
}
console.log(score); //print out score array in console
console.log(message); //print out message string in console
if (isValid) {
//step2.3: add js so that when all inputted test scores are valid, compute total points, average points (with zero decimal place), and
//final letter grade, and display them in the input boxes in the <div> element with id=’result’ on the web page.
for (var j = 0; j < numInputs; j++) {
totalscore += score[j];
}
totalscore = totalscore.toFixed(1);
avgScore = totalscore / numInputs;
avgScore = avgScore.toFixed(1);
var scoreTotal = document.getElementById('scoreTotal');
scoreTotal.value = totalscore.toString();
var scoreAvg = document.getElementById('scoreAvg');
scoreAvg.value = avgScore.toString();
avgScore = parseFloat(avgScore);
if (avgScore <= 150 && avgScore >= 120)
finalScore = "A";
else if (avgScore < 120 && avgScore >= 100)
finalScore = "B";
else if (avgScore < 100 && avgScore >= 80)
finalScore = "C";
else if (avgScore < 80 && avgScore >= 60)
finalScore = "D";
else if (avgScore < 60)
finalScore = "F";
var scoreFinal = document.getElementById("scoreFinal")
scoreFinal.value = finalScore
} else {
//If not all inputted test scores are valid, then create an alert box to display an error message
alert(message);
}
}; //end of processEntries function
//each time when calculate button is clicked, inputted test scores will be evaluated and
$("calculate").onclick = function() {
if (numInputs > 0 && numInputs < 6)
processEntries();
};
$("numscores").focus();
#import url(http://fonts.googleapis.com/css?family=Wellfleet);
body {
font-family: 'Wellfleet', Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 60%;
min-width: 600px;
border: 3px solid blue;
padding: 0 1em .5em;
}
h1 {
color: blue;
margin: .5em 0;
}
#teacher {
float: right;
margin: 0px 30px 0px 0px;
}
label {
float: left;
width: 10em;
text-align: right;
margin-bottom: .5em;
}
input {
width: 5em;
margin-left: 1em;
margin-bottom: .5em;
}
input.error {
background-color: yellow;
}
#s1 {
display: inline-block;
}
#s1 input {
vertical-align: center;
float: left;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test Score App</title>
<link rel="stylesheet" href="score.css">
</head>
<body>
<main>
<h2>The Test Scores App</h2>
<img src="teacher.png" id="teacher" alt="teacher" width="177" height="277">
<div id="s1">
<label for="numscores">How many tests you want to consider?</label>
<input type='number' id='numscores' min='1' max='10' value='1'>
</div>
<div id="testInputs">
<label for="score1">Test-1:</label>
<input type='number' id='score1' value='150' /><br>
</div>
<div id='result'>
<label for="scoreTotal">Total Points:</label>
<input type="number" id="scoreTotal" disabled><br>
<label for="scoreAvg">Avg Grade:</label>
<input type="number" id="scoreAvg" disabled><br>
<label for="scoreFinal">Final Letter Grade:</label>
<input type="text" id="scoreFinal" disabled><br>
<label> </label>
<input type="button" id="calculate" value="Calculate">
</div>
</main>
<script src="testScoreV2.js">
</script>
</body>
</html>
Here is the javascript for calculating the price of the item the problem is that
whenever the price is 4 digits the value that return is NaN.
here's my hidden field for the price:
<input type="hidden" name="price" id="price"class="price" value="4500"readonly >
here's for my quantity field
<input type="number" name="quant" id="quant" value="2" />
here's for my shipment fee
<select id="shipment" onchange="myFunction3()" name="shipment2" disabled>
<option value="100" data-quantity="1">1 for 100 pesos </option>
</select
here's for the total price
<input type="text" id="demo" name="total_price" style="margin-top:10px;margin-left:5px;" readonly>
Script for changing the value of shipment
<script type="text/javascript">
document.getElementById('quant').addEventListener("keyup", function(){
var value = parseInt(this.value, 20),
selectEle = document.getElementsByTagName('select')[0],
options = selectEle.options,
selectedNum = 0;
for(var i = 0; i < options.length; i++) {
//checking the exact string with spaces (" " + value + " ")
if(options[i].textContent.indexOf(" " + value + " ") > -1) {
selectedNum = i;
}
}
selectEle.selectedIndex = selectedNum ? selectedNum : 0;
}, false);
</script>
Calculating all the values
function myFunction3() {
var y= document.getElementById("shipment").value;
return y;
}
<script>
$("#price,#quant,#shipment").keyup(function () {
if(+myFunction3() =="" )
{
$('#demo').val(0);
}
else if($('#trigger')=="checked") //this is the problem
{
$('#demo').val($('#price').val() * $('#quant').val() ;
}
else
{
$('#demo').val($('#price').val() * $('#quant').val() + +myFunction3());
}
});
</script>
Not sure if this was just typed incorrectly in here, but you have a syntax error (missing closing parenthesis) near the problem area:
$('#demo').val($('#price').val() * $('#quant').val() ;
Should be:
$('#demo').val($('#price').val() * $('#quant').val());
I think it would be much better to ensure you aren't working with strings before you do math on them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
$('#demo').val(price * quantity);
You could go further and ensure that neither of them are NaN prior to working with them:
var price = parseInt($('#price').val(), 10);
var quantity = parseInt($('#quant').val(), 10);
if(!isNaN(price) && !isNaN(quantity)) {
$('#demo').val(price * quantity);
} else {
alert('Please enter numbers only!');
}
I have an error in my code.
The objective is that if the user buys enough jersey's that is over €250 I have to discount everything that comes next after it at 15%.
The first part of my code works (If cost <= 250) the anything above gives me a (NaN).
My code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>
Q1 - Jerseys
</title>
<style type="text/css">
</style>
<script>
"use strict";
function processOrder()
{
//Calculations for Order
var type = document.getElementById("getType").value;
var number = parseInt(document.getElementById("getNumber").value);
var cost;
var PER_FIVE = parseFloat(0.15);
var overPrice = cost - 250;
//Logo Variables
var logo = document.getElementById("getLogo").value || "N";
var logoCost = 1.50;
//Empty Variables for Returned Values
var outputText;
//Polo Shirt Case
if (type === "Polo" && logo === "Y")
{
cost = (number * (22.50 + logoCost));
} else if (type === "Polo" && logo === "N") {
cost = parseFloat(number * 22.50);
}//End Polo
//Short Sleeve Case
if (type === "Short" && logo === "Y") {
cost = (number * (22.50 + logoCost));
} else if (type === "Short" && logo === "N") {
cost = number * 25.50;
}//End Short
//Long Sleeve Case
if (type === "Long" && logo === "Y") {
cost = (number * (22.50 + logoCost));
} else if (type === "Long" && logo === "N") {
cost = number * 28.50;
}//End Long
//Output To "results" Text Area
if (cost <= 250) {
outputText = "The cost of your jerseys is €" + cost;
document.getElementById("results").value = outputText;
} else if (cost > 250) {
outputText = "The cost of your jerseys is €" + (250 + (overPrice - (overPrice * PER_FIVE)));
document.getElementById("results").value = outputText;
}//End If
}//End Function
</script>
</head>
<body>
Please Enter details of your jersey order:
<br> <br>
Type of jersey (Polo, Short,Long):
<input id="getType" />
<br> <br>
Number of Jerseys:
<input id="getNumber" />
<br> <br>
Add A Logo:
<input id="getLogo" maxlength="1"/> Type: "Y" or "N".
<br> <br>
<button onclick="processOrder()" >Click to see results below</button>
<br> <br>
Results:
<br>
<textarea id="results" rows="4" cols="50" readonly >
</textarea>
</body>
</html>
You're assigning overPrice before cost has been determined:
var overPrice = cost - 250;
At this point cost is undefined, and undefined - 250 is what's giving you NaN.
Variables aren't dynamic in this way - updating cost won't automatically update overPrice - you need to set it once you know the value of cost. Within your else if block would be appropriate since it is not needed elsewhere:
//Output To "results" Text Area
if (cost <= 250) {
outputText = "The cost of your jerseys is €" + cost;
document.getElementById("results").value = outputText;
} else if (cost > 250) {
var overPrice = cost - 250;
outputText = "The cost of your jerseys is €" + (250 + (overPrice - (overPrice * PER_FIVE)));
document.getElementById("results").value = outputText;
}//End If
On a separate note, you're using parseInt without specifying the radix parameter. It's recommended to always specify it to avoid potential issues:
var number = parseInt(document.getElementById("getNumber").value, 10);
I am looking to make price calculator for editing papers. I have the first part complete (words per day jsfiddle ).
<label>Need in how many Days</label>
<input type="number" id="days" />
<br />
<label>Total Word Count</label>
<input type="number" id="words" />
<br />
<label>Price</label>
<input type="text" id="output" readonly />
I am looking to have the user enter the total word count and how many days they need the document, to display the price per project. I am not sure how to add the price table to the javascript and have it display the results. The table is:
250 words or less = $0.015 per word, 251-499 = $0.020 per word, 500-1499 = $0.025 per word, 1500-2499 = $0.030 per word, More than 2500 words per day = contact me
Thanks for the help. Hope that makes sense.
I have tried to do it as explicitly as possible in pure Javascript for easier understanding.
This is the HTML:
<label>Need in how many Days</label>
<input type="number" onkeyup="getValues()" id="days" />
<br />
<label>Total Word Count</label>
<input type="number" onkeyup="getValues()" id="words" />
<br />
<label>Price</label>
<input type="text" id="output" readonly />
<br />
And here is the JavaScript:
var days, words, output;
//think of the prices as t-shirt sizes
var extraSmall = 0.015,
small = 0.020,
medium = 0.025,
large = 0.030,
extraLarge = 0.035,
extraExtraLarge = 'contact me';
// now you go into the dom and get the values you need
window.getValues = function () {
var pricePerWord = 0;
days = document.getElementById('days').value;
words = document.getElementById('words').value;
if(words > 2500) {
if(days == 1) {
pricePerWord = extraExtraLarge;
} else {
pricePerWord = extraLarge;
}
} else if (words >= 1500) {
pricePerWord = large;
} else if (words >= 500) {
pricePerWord = medium;
} else if (words >= 251) {
pricePerWord = small;
} else {
pricePerWord = extraSmall;
}
// call the calculate function to do the math and update the dom
calculate(pricePerWord, words, days);
}
window.calculate = function (pricePerWord, words, days) {
var total;
if(pricePerWord === extraExtraLarge) {
total = extraExtraLarge;
} else {
total = Math.ceil(pricePerWord * words / days);
}
output = document.getElementById('output');
if(days !== '' && days != 0) {
output.value = total;
} else {
output.value = 0; // prevent 'Nan' and 'Infinity' from showing up
}
}
Note: The code uses 'window.calculate' as it makes it work in jsfidle but it should work without the 'window.' part in your code.
Hope it helps!