Javascript: assigning an input letter a specific value - javascript

I'm having trouble assigning an input a certain value. For example, when the user enters a letter through the TicketType prompt, I want that letter to be converted into a number. So say they enter 'B' as their TicketType, I then want 'B' to be converted into 50 so I can latter calculate a total cost. At the moment TotalPayment is only displaying NaN and I'm so confused.
This is my JavaScript Code:
function ticket() {
var TicketType;
TicketType = prompt("Please enter the type of ticket you require!");
document.write("<br>");
var TicketQty;
TicketQty = prompt("Please enter the number of tickets you require!");
TicketQty = parseInt(TicketQty);
document.write("Number of Tickets:" + TicketQty);
document.write("<br>");
var TotalPayment =(TicketPrice) * (TicketQty);
document.write("Total Payment is:" + TotalPayment);
var TicketPrice;
TicketPrice = parseInt(TicketPrice);
if (TicketType == A) {
TicketPrice == 100;
}
else if (TicketType == B) {
TicketPrice == 75;
}
else if (TicketType == C){
TicketPrice == 50;
}
else {
document.write("Invalid Ticket Type");
}
}
This is my HTML Code:
<html>
<title>Ticket</title>
<h1>Ticket</h1>
<script src="test.js"> </script>
<script>calculate()</script>
</body>

Try the following:
var TicketType;
var TicketQty;
var TicketPrice;
function calculateticket() {
TicketType = prompt("Please enter the type of ticket you require!");
document.write("<br>");
TicketQty = prompt("Please enter the number of tickets you require!");
testType();
}
calculateticket();
function testType(){
if(TicketType =='A' || TicketType == 'B' || TicketType == 'C'){
if (TicketType == 'A') {
TicketPrice = 100;
} else if (TicketType == 'B') {
TicketPrice = 75;
} else if (TicketType == 'C'){
TicketPrice = 50;
}
TicketQty = parseInt(TicketQty);
document.body.innerHTML += '<span id="text1"></span>';
document.getElementById('text1').innerHTML = 'Total Payment is: '+TicketQty;
document.write("<br>");
var TotalPayment =(TicketPrice) * (TicketQty);
document.body.innerHTML += '<span id="text2"></span>';
document.getElementById('text2').innerHTML = 'Total Payment is: '+TotalPayment;
TicketPrice = parseInt(TicketPrice);
}
else {
if(document.getElementById('text1') != null){
document.getElementById('text1').innerHTML = '';
}
if(document.getElementById('text2') != null){
document.getElementById('text2').innerHTML = '';
}
document.write("Invalid Ticket Type");
}
}

You need to change two things:
1: String comparation
if (TicketType == A)
to
if (TicketType == 'A')
2: wrong assign
TicketPrice == 100
to
TicketPrice = 100

Your string comparison is completely wrong. I'm confining my answer to that because it's what you were asking about.
if (TicketType == A) {
Needs to be:
if (TicketType === "A") {
Also, you have to be clear on assignment '=' vs. comparison '=='.
Whole section should be more like this:
if (TicketType === "A") {
TicketPrice = 100;
} else if (TicketType === "B") {
TicketPrice = 75;
} else if (TicketType === "C")
TicketPrice = 50;
else {
document.write("Invalid Ticket Type");
}
Look into switch statements when you have a chained if-then-elseif
There are other things wrong with your code. Here's a jsfiddle with some fixes and improvements.

Related

NaN appears when trying to calculate price

I am new to programming, and am trying to create a simple mathematical script that determines the price of the game the user selects and multiplies that by the number of days they wish to reserve the game.
It works, but the final price always comes out as 'NaN' (which I believe stands for 'Not a Number').
Any help will be greatly appreciated.
<html>
<body>
<p><strong>Game ID</strong><br>
<input type="number" name="gameID" id="gameID" placeholder="1-8">
<p><strong>Days you wish to reserve the game for</strong><br>
<input type="number" name="daysReserved" id="daysReserved" placeholder="1-5">
<br>
<button type="button" onclick="idToPrice();finalPriceCalculation();">Reserve!</button>
<p id="totalPriceOutput"></p>
<script>
function idToPrice() {
var id = document.getElementById("gameID").value;
if (id == 1) {
var gamePrice = 0.99;
} else if (id == 2) {
var gamePrice = 0.99;
} else if (id == 3) {
var gamePrice = 1.99;
} else if (id == 4) {
var gamePrice = 1.99;
} else if (id == 5) {
var gamePrice = 3.99;
} else if (id == 6) {
var gamePrice = 3.99;
} else if (id == 7) {
var gamePrice = 0.99;
} else if (id == 8) {
var gamePrice = 0.99;
} else {
document.getElementById("totalPriceOutput").innerHTML = "Error. Your final price could not be calculated because you selected an invalid game ID.";
}
}
function finalPriceCalculation() {
var daysInputted;
var gamePrice;
var finalPrice = daysInputted * gamePrice;
document.getElementById("totalPriceOutput").innerHTML = "Your final price is £" + finalPrice + ".";
}
</script>
</body>
</html>
NOTE: There were 3 problems in your code. I have corrected them all, plus modified conditionals using switch case statements for better readability.
1. In your this code, your var daysInputted and var gamePrice are both local.
var daysInputted;
var gamePrice;
var finalPrice = daysInputted * gamePrice;
You might be thinking when you are calling idToPrice() method first so gamePrice must be defined. But it is not so.
Because when you say var gamePrice inside a method, gamePrice becomes a local variable for that method and it is not accessible in any other method.
Hence you either need to define both the variables inside the same method or make them global in the idToPrice() method.
2. You also need to define daysInputted as
var daysInputted = document.getElementById("daysReserved").value;
3. you also need to parse document.getElementById("gameID").value to Integer
Your final code fully working code will be
<body>
<p><strong>Game ID</strong><br>
<input type="number" name="gameID" id="gameID" placeholder="1-8">
<p><strong>Days you wish to reserve the game for</strong><br>
<input type="number" name="daysReserved" id="daysReserved" placeholder="1-5">
<br>
<button type="button" onclick="idToPrice();finalPriceCalculation();">Reserve!</button>
<p id="totalPriceOutput"></p>
<script>
function idToPrice() {
var id = parseInt(document.getElementById("gameID").value);
switch(id) {
case 1:
gamePrice = 0.99;
break;
case 2:
gamePrice = 0.99;
break;
case 3:
gamePrice = 1.99;
break;
case 4:
gamePrice = 1.99;
break;
case 5:
gamePrice = 3.99;
break;
case 6:
gamePrice = 3.99;
break;
case 7:
gamePrice = 0.99;
break;
case 8:
gamePrice = 0.99;
break;
default:
document.getElementById("totalPriceOutput").innerHTML = "Error. Your final price could not be calculated because you selected an invalid game ID.";
break;
}
}
function finalPriceCalculation() {
var daysInputted = document.getElementById("daysReserved").value;
var finalPrice = daysInputted * gamePrice;
document.getElementById("totalPriceOutput").innerHTML = "Your final price is £" + finalPrice + ".";
}
</script>
</body>
daysInputted is not being assigned a number so it's undefined, so you are multiplying with undefined, hence NaN
Found problem
The variables are not getting value,
Didnt use parseInt() to get integer values
Complete code modified, tested and works 100%
<html>
<body>
<p><strong>Game ID</strong><br>
<input type="number" name="gameID" id="gameID" placeholder="1-8">
<p><strong>Days you wish to reserve the game for</strong><br>
<input type="number" name="daysReserved" id="daysReserved" placeholder="1-5">
<br>
<button type="button" onclick="idToPrice();">Reserve!</button>
<p id="totalPriceOutput"></p>
<script>
function idToPrice() {
var id = parseInt(document.getElementById("gameID").value);
var days = parseInt(document.getElementById("daysReserved").value);
if(!isNaN(id))
{
if (id == 1) {
var gamePrice = 0.99;
} else if (id == 2) {
var gamePrice = 0.99;
} else if (id == 3) {
var gamePrice = 1.99;
} else if (id == 4) {
var gamePrice = 1.99;
} else if (id == 5) {
var gamePrice = 3.99;
} else if (id == 6) {
var gamePrice = 3.99;
} else if (id == 7) {
var gamePrice = 0.99;
} else if (id == 8) {
var gamePrice = 0.99;
}
finalPriceCalculation(id,days);
}
else {
document.getElementById("totalPriceOutput").innerHTML = "Error. Your final price could not be calculated because you selected an invalid game ID.";
}
}
function finalPriceCalculation(gamePrice,daysInputted) {
var daysInputted;
var finalPrice = parseInt(daysInputted) * parseInt(gamePrice);
document.getElementById("totalPriceOutput").innerHTML = "Your final price is £" + finalPrice + ".";
}
</script>
Your JS code could be:
function idToPrice() {
var id = document.getElementById("gameID").value,
gamePrice, daysInputted, finalPrice; //It is a good practice to define variables at the top of the function, check "variable hoisting".
if (id === 1) { // It is a good practice to use "===" for checking value and type
gamePrice = 0.99;
} else if (id === 2) {
gamePrice = 0.99;
} else if (id === 3) {
gamePrice = 1.99;
} else if (id === 4) {
gamePrice = 1.99;
} else if (id === 5) {
gamePrice = 3.99;
} else if (id === 6) {
gamePrice = 3.99;
} else if (id === 7) {
gamePrice = 0.99;
} else if (id === 8) {
gamePrice = 0.99;
}
if (gamePrice) {
daysInputted = document.getElementById("daysReserved").value || 0;
finalPrice = daysInputted * gamePrice;
}
if (finalPrice) {
document.getElementById("totalPriceOutput").innerHTML = "Your final price is £" + finalPrice + ".";
} else {
document.getElementById("totalPriceOutput").innerHTML = "Error. Your final price could not be calculated because you selected an invalid game ID.";
}
}
And, your HTML code:
<button type="button" onclick="idToPrice()">Reserve!</button>

NaN error equation

In this javascript code I try to solve a quadratic equation, I've been working on it for an hour and this should tell me the value of a, b and c where y is a(x^2). I'm a relative javascript beginner and would love some help. Why are the values of a, b and c not numbers? The variable names are in italian, in english and in something else(Not even I know what), but I commented what they are. That's one of my bad traits as a student that usually works alone, sorry if it's not easy to understand.
<script type="text/javascript">
var equa=prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var a = 0.0; b = 0.0; c = 0.0;//ax2+bx+c
var prima = true; //before or after equal?
var ope = 1;//1add 2sub 3mul 4div
var lasto = 0.0;//last number, used for div and mul
var lastos = 3; //1a2b3c
var errore=0;//is something messed up?
for(var i = 0; i < equa.length;i=i){
if(equa.charAt(i)=='='){
prima = false;
i++;
}else if(equa.charAt(i)=='+'){
ope=1;
i++;
}else if(equa.charAt(i)=='-'){
ope=2;
i++;
}else if(equa.charAt(i)=='*'){
ope=3;
i++;
}else if(equa.charAt(i)=='/'){
ope=4;
i++;
}else{
var nume = "";//Current number in string form
while(i<equa.length && equa.charAt(i)>'0' && equa.charAt(i)<'9'){
nume+=equa.charAt(i);
i++;
}
var lasnum = 0.0;//current number in float form
var lasval = 3; //1a2b3c
if(equa.charAt(i) == 'x'){
lasnum=parseFloat(nume);
lasval = 2;
}else if(equa.charAt(i) == 'y'){
lasnum=parseFloat(nume);
lasval = 1;
}else{
lasnum = parseFloat(nume);
lasval=3;
}
i++;
if( (ope == 1 || ope == 2) && !(equa.charAt(i) =='*' || equa.charAt(i) == '/')){
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
}else if( (ope==1 || ope == 2) && (equa.charAt(i) =='*' || equa.charAt(i) == '/')){
//zitto e fermo
lasto=lasnum;
lastos=lasval;
}else if( (ope==3||ope == 4)){
if(ope==3){
if(lastos==3){
lasnum*=lasto;
}
if(lastos == 2){
if(lastval==3){
lasnum*=lasto;
lastval=2;
}
if(lastval==2){
lasnum*=lasto;
lastval=1;
}
if(lastval==1){
errore=1;
}
}
if(lastos == 1){
if(lastval == 3){
lasnum*=lasto;
lastval=1;
}else{
errore=1;
}
}
}
if(ope == 4){
if(lastos == 1){
if(lastval==3){
lasnum/=lasto;
lastval=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=2;
}
if(lastval==1){
lasnum/=lasto;
lastval=3;
}
}
if(lastos == 2){
if(lastval==1){
errore=1;
}
if(lastval==2){
lasnum/=lasto;
lastval=3;
}
if(lastval==3){
lasnum/=lasto;
lastval=2;
}
}
if(lastos == 3){
if(lastval==3){
lasnum/=lasto;
}else{
errore=1;
}
}
}
if(equa.charAt(i) =='*' || equa.charAt(i) == '/'){
lasto=lasnum;
lasto=lasval;
}else{
if(lasval == 1){
if(prima) a+=lasnum;
else a-=lasnum;
}
else if(lasval == 2){
if(prima) b+=lasnum;
else b-=lasnum;
}
else {
if(prima) c+=lasnum;
else c-=lasnum;
}
lasto=0;
lastos=3;
}
}
}
}
if(errore==0){
alert("a ="+a+" b="+b+" c="+c);
}else{
alert("AOOOOOOo");
}
</script>
Since the expected input should be in the format "15y+3x+5=20" for example, then this is a simple regular expression:
var equa = prompt("Scrivi l'equazione senza spazi usando x come incognita e y come x^2");
var regex = /^([0-9.]+)y\+([0-9.]+)x\+([0-9.]+)=([0-9.]+)$/;
var matches = regex.exec(equa);
if (matches) {
var a = parseFloat(matches[1]);
var b = parseFloat(matches[2]);
var c = parseFloat(matches[3]) - parseFloat(matches[4]);
var discriminant = b*b - 4*a*c;
if (discriminant < 0) {
alert('No real solutions');
}
else {
var root = Math.sqrt(discriminant);
alert('Root: ' + ((-b + root)/(2*a)) + ', ' + ((-b - root)/(2*a)));
}
}
else {
alert("AOOOOOOo");
}

four repeating letters check javascript, spam detection

Is there a a "smarter" way to do this? This works but I imagine has something to do with for loops, what if I was checking for 20 repeating characters?
What happens if javascript is disabled?
Is there an easier way to check for "sensical" posts instead of say aldjfalkfja;lfjaklfjlkfj how would I filter that out without storing a library of words and comparing the string to those?
function counter(){
this.value = 0;
}
var count = new counter();
function updatecount(fnc){
fnc.value = count.value + 1;
}
function charbank1(){
this.value = "";
}
var cb1 = new charbank1();
function insertchar1(fnc){
fnc.value = cb1.value + String.fromCharCode(keynum);
}
function charbank2(){
this.value = "";
}
var cb2 = new charbank2();
function insertchar2(fnc){
fnc.value = cb2.value + String.fromCharCode(keynum);
}
function charbank3(){
this.value = "";
}
var cb3 = new charbank3();
function insertchar3(fnc){
fnc.value = cb3.value + String.fromCharCode(keynum);
}
function charbank4(){
this.value = "";
}
var cb4 = new charbank4();
function insertchar1(fnc){
fnc.value = cb4.value + String.fromCharCode(keynum);
}
function repeatingcharcheck(){
if(count.value < 4){
if(count.value == 1){
insertchar1(cb1);
}
if(count.value == 2){
insertchar2(cb2);
}
if(count.value == 3){
insertchar3(cb3);
}
if(count.value == 4){
insertchar4(cb4);
}
}else{
if(cb1.value == cb2.value == cb3.value == cb4.value){
alert('four letters in a row is not allowed');
window.location.replace('somewhere.com');
}
}
}

My javascript loop breaks before it gets through all if else statements

I'm trying to write a pin number guessing game and wrote out a bunch of if else statements but it stops working after I input the first pin (correct or incorrect), can anyone tell me what's going on?
var ans = prompt("Do you want to play?");
if (ans == "y") {
document.getElementById("ans").innerHTML = "You answered yes.";
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h1;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h2;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = h3;
guessNum();
if (gNum != pswd) {
document.getElementById("hint").innerHTML = "You lost. :(";
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("hint").innerHTML = "You guessed the pin!";}
} else {
document.getElementById("ans").innerHTML = "You answered no.";}
Here is the rest of the javascript but I don't think the problem lies there.
var nums = [0, 0, 0, 0];
for (var idx = 0; idx < nums.length; ++idx)
{
nums[idx] = Math.floor((Math.random() * 9) + 1);
}
pswd = nums.join("")
document.getElementById("nums").innerHTML = pswd;
function guessNum() {
var gNum = prompt("What do you think the number is?")
}
if (nums[3] % 2 == 0) {
var divis = "even";
} else {
var divis = "odd";
}
var h1 = "The first number is " + nums[0]
var h2 = "The sum of the middle numbers are " + (nums[1] + nums[2])
var h3 = "The last number is " + divis
The problem is that the variable gNum that you're creating inside the guessNum function only lives there. Javascript is function scoped.
When you get to the line if (gNum != pswd) {... gNum simply doesn't exist. Make guessNum return the value, and create the actual gNum variable on the same scope as the if.
function guessNum() {
return prompt("What do you think the number is?")
}
...
var gNum = guessNum();
if (gNum != pswd) {
...
I would also advise you to study while loops, to avoid these nested ifs. Keep the hard work! :)

Javascript: Mathfloor still generating a 0

In my script to generate a playing card, it's generating a 0, even though my random generator is adding a 1, so it should never be 0. What am I doing wrong?! If you refresh, you'll eventually get a "0 of Hearts/Clubs/Diamonds/Spades":
var theSuit;
var theFace;
var theValue;
var theCard;
// deal a card
function generateCard() {
var randomCard = Math.floor(Math.random()*52+1)+1;
return randomCard;
};
function calculateSuit(card) {
if (card <= 13) {
theSuit = "Hearts";
} else if ((card > 13) && (card <= 26)) {
theSuit = "Clubs";
} else if ((card > 26) && (card <= 39)) {
theSuit = "Diamonds";
} else {
theSuit = "Spades";
};
return theSuit;
};
function calculateFaceAndValue(card) {
if (card%13 === 1) {
theFace = "Ace";
theValue = 11;
} else if (card%13 === 13) {
theFace = "King";
theValue = 10;
} else if (card%13 === 12) {
theFace = "Queen";
theValue = 10;
} else if (card%13 === 11) {
theFace = "Jack";
theValue = 10;
} else {
theFace = card%13;
theValue = card%13;
};
return theFace;
return theValue
};
function getCard() {
var randomCard = generateCard();
var theCard = calculateFaceAndValue(randomCard);
var theSuit = calculateSuit(randomCard);
return theCard + " of " + theSuit + " (this card's value is " + theValue + ")";
};
// begin play
var myCard = getCard();
document.write(myCard);`
This line is problematic:
} else if (card%13 === 13) {
Think about it: how a remainder of division to 13 might be equal to 13? ) It may be equal to zero (and that's what happens when you get '0 of... '), but will never be greater than 12 - by the very defition of remainder operation. )
Btw, +1 in generateCard() is not necessary: the 0..51 still give you the same range of cards as 1..52, I suppose.
card%13 === 13
This will evaluate to 0 if card is 13. a % n will never be n. I think you meant:
card % 13 === 0
return theFace;
return theValue
return exits the function; you'll never get to the second statement.

Categories

Resources