I'm working through Beginning Javascript but can't get past Chapter 2 finishing exercise 2. The exercise is to correct this bit of code
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 2, Finishing exercise 2</title>
</head>
<body>
<script>
var firstNumber = prompt("Enter the first number", "");
var secondNumber = prompt("Enter the second number", "");
var theTotal = firstNumber + secondNumber;
document.write(firstNumber + " added to " + secondNumber + " equals " theTotal);
</script>
</body>
</html>
I can get the correct total to display using alert, however when I remove the commenting it no longer works.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 2, Finishing exercise 2</title>
</head>
<body>
<script>
var firstNumber = prompt("Enter the first number", "");
var secondNumber = prompt("Enter the second number", "");
var intFirstNumber = parseInt(firstNumber, 10);
var intSecondNumber = parseInt(secondNumber, 10);
var theTotal = intFirstNumber + intSecondNumber;
alert(theTotal);
//document.write (intFirstNumber + " added to " + intSecondNumber + " equals " theTotal);
</script>
</body>
</html>
I can't figure out what about my document.write statement is wrong. Any hints? Additionally is there a more elegant way to achieve what I'm doing?
You need another + between the "equals" and theTotal:
document.write(firstNumber + " added to " + secondNumber + " equals " + theTotal);
In this context, the + sign means concatenate (append) whatever comes after it to whatever comes before it.
Further Reading:
MDN documentation for string concatenation.
Related
I'm currently attempting to use the Flickr API and javascript to generate a page based on a search query, in this case, dogs. When the line
var hyperLink = "https://www.flickr.com/photos/" + photo.owner + "/" + photo.id + ".jpg";
Runs it states undefined is not an object in regards to photo.owner. I am able to print out photo.owner using console.log(photo.owner) but cannot access it to merely print out the information in the url.
Full code is:
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Flickr Experiment</title>
</head>
<body id ="1">
<script>
function jsonFlickrApi(rsp) {
var str = "";
str +="<h1>Doggo piccies from Flickr</h1>";
str +="<h3>Total piccies: " + rsp.photos.photo.length;
var i;
for (i = 0; i <= rsp.photos.photo.length; i++) {
var photo = rsp.photos.photo[i];
var imageTitle = photo.title;
var hyperLink = "https://www.flickr.com/photos/" + photo.owner + "/" + photo.id + ".jpg";
var imgLink = "https://farm" + photo.farm + ".staticflickr.com/" + photo.server + "/" + photo.id + "_" + photo.secret + "_t.jpg";
str +="<img alt=\"" + imageTitle + "\" src=\"" + imgLink + "\"/>"
}
document.writeln(str);
}
</script>
<script src="https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=XXXXf&tags=golden-retriever&per_page=100&format=json">
</script>
</body>
</html>
Arrays are zero based. That means if an array's length is 3, then the highest index is 2. The loop condition must therefore be
i < rsp.photos.photo.length
//^^ strictly smaller, not smaller or equal
If not, you will be accessing an index (namely the length of the array) which doesn't exist, which will result in undefined, the error you are getting.
Simple example:
var arr = [1,2,3];
console.log(arr[0]);
console.log(arr[1]);
console.log(arr[2]);
console.log(arr[arr.length]);
So i've been trying to debug this for a few hours and I'm completely stuck. When I go on the webpage I get this error in the console:
(Cannot read property 'value' of null at totalCost (assn1.html:18) at assn1.html:26 totalCost # assn1.html:18
(anonymous) # assn1.html:26.
My program is all finished I just can't get it to call the function and print the name, number of cups and the total cost at the end.
Heres my code:
<html>
<head>
<title>Tea Shoppe</title>
</head>
<body>
<section>
<h1> Welcome to the Tea Shoppe!</h1>
<p>
<img src = "http://nobacks.com/wp-content/uploads/2014/11/Tea-Cup-5-500x476.png" />
</p>
</section>
<script>
function totalCost()
{
var cups = parseInt(document.getElementById("cups").value);
var tax = (cups * 9 ) /100;
var totalAmount = parseFloat(cups + tax).toFixed(2);
return totalAmount;
}
var name = prompt("Please enter your name");
var cups = prompt("Ok " + name + ", how many cups of tea would you like?");
totalCost(cups);
document.write("Ok" + name + ", you ordered" + cups + " of tea" + "your total price is" + totalCost);
</script>
</body>
</html>
document.getElementById("cups")
You have no element with that ID in your document.
function totalCost(cups)
{
var tax = (cups * 9 ) /100;
var totalAmount = parseFloat(cups + tax).toFixed(2);
return totalAmount;
}
var name = prompt("Please enter your name");
var cups = prompt("Ok " + name + ", how many cups of tea would you like?");
document.write("Ok " + name + ", you ordered" + cups + " of tea" + " your total price is " + totalCost(cups));
Here's a working version of your code, what i did here is adding teh totalcost function parameter since you pass it when you call the function and got rid of the cups variable inside your function because it has nothing to do there and was causing an error also + and changed the place where you function should be called from since it returns the totalcups value it must be put inside the document.write function to return the total in it's perfect place.
that's all and i hope this fixed your problem.
herre's a working fiddle https://jsfiddle.net/bgn4x7ej/
This is the link to the viewable example from the book;http://beginningjs.com/examples/ch2_example7.html
This is my code saved locally; Not sure why it wont load.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title> Chapter 2, Example 7</title>
</head>
<body>
<script>
var myString = "56.02 degrees centigrade";
var myInt;
var myFloat;
document.write{"\"" + myString + "\" is + "\" + parseInt(myString, 10) +
"as an interger" + "<br/>"};
myInt = parseInt(myString, 10);
document.write("\"" + myString + "\"when converted to an interger equals " + myInt + "<br/>" );
nyFloat = parseFloat(myString);
document.write( "\"" + myString + "\" when converted to a floating point number equals " + myFloat);
document.write(myString);
</script>
</body>
</html>
I think it's loaded but your javascript syntax are wrong.
Use parentheses instead of braces on your first document.write. The script is stuck in that line and the rest of your program doesn't execute, that's why the page doesn't show anything.
Okay There is an error in your first document.write("your string") line you need to use small () braces instead of curly {} braces every time you use document.write("your string"). You have declared variable as var myFloat; and then used it as nyFloat = parseFloat(myString); which is wrong because of typo in nyFloat and (mystring,10) to print value 56.02 at the end. so the correct is myFloat = parseFloat(myString,10); There is no need to write the last line i.e. document.Write(myString); as it is printing the string again at the end. If in future you experience these kind of errors you can see these Javascript errors by using developer tool in your browser and for that you just need to press F12 from your key board as explained in one of comment under your question.
Here is the corrected code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title> Chapter 2, Example 7</title>
</head>
<body>
<script>
var myString = "56.02 degrees centigrade";
var myInt;
var myFloat;
document.write("\"" + myString + "\" is " + parseInt(myString, 10) + " as an interger" + "<br/>");
myInt = parseInt(myString, 10);
document.write("\"" + myString + "\" when converted to an interger equals " + myInt + "<br/>" );
myFloat = parseFloat(myString, 10);
document.write("\"" + myString + "\" when converted to a floating point number equals " + myFloat);
//document.write(myString);
</script>
</body>
</html>
Learning JS from a book, the exercise question was this:
Modify the code of Question 1 to request the times table to be displayed from the user; the code
should continue to request and display times tables until the user enters ‐1. Additionally, do a check
to make sure that the user is entering a valid number; if the number is not valid, ask the user to
re‐enter it.
This is the proposed solution:
function writeTimesTable(timesTable, timesByStart, timesByEnd) {
for (; timesByStart <= timesByEnd; timesByStart++) {
document.write(timesTable + " * " + timesByStart + " = " +
timesByStart * timesTable + "<br />");
}
}
var timesTable;
while ((timesTable = prompt("Enter the times table", -1)) != -1) {
while (isNaN(timesTable) == true) {
timesTable = prompt(timesTable + " is not a " +
"valid number, please retry", -1);
}
if (timesTable == -1) {
break;
}
document.write("<br />The " + timesTable +
" times table<br />");
writeTimesTable(timesTable, 1, 12);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 4: Question 2</title>
</head>
<body>
<script>
</script>
</body>
</html>
This is my code, which also runs with the same result, without != -1:
function writeTimesTable(timesTable, timesByStart, timesByEnd) {
for (; timesByStart <= timesByEnd; timesByStart++) {
document.write(timesTable + " * " + timesByStart + " = " +
timesByStart * timesTable + "<br />");
}
}
var timesTable;
while (timesTable = prompt("Enter the times table", -1)) {
while (isNaN(timesTable) == true) {
timesTable = prompt(timesTable + " is not a " +
"valid number, please retry", -1);
}
if (timesTable == -1) {
break;
}
document.write("<br />The " + timesTable +
" times table<br />");
writeTimesTable(timesTable, 1, 15);
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chapter 4: Question 2</title>
</head>
<body>
<script>
</script>
</body>
</html>
Why do I need != -1 parameter in the first while statement, since my code runs perfectly fine? Why is it there, what is it for?
The check for -1 is almost but not quite superfluous. It catches the conditions 'user canceled prompt' and 'user entered an empty string' which evaluates to false. In your version, this terminates the loop but the requirement is to terminate at user input '-1'.
If a while loop doesn't return anything, it will return as -1 (or false). In the case of the original example, I assume that the != -1 condition is there for example purposes only so it makes more sense to a beginner.
Let's say you were only wanting to terminate the while loop when the user entered -2. To do that, you would need to specify the != -2 condition in the loop, but -1 would still terminate the loop.
You're telling the browser/compiler to keep executing the code in the while loop until the user enters -1. When timesTable gets the value "-1" - that is, when the user enters "-1" - the while loop stops running.
// timesTable gets what the user enters in the prompt
// while timesTable is not equal to -1, execute the code in brackets
while ((timesTable = prompt("Enter the times table", -1)) != -1) {
while (isNaN(timesTable) == true) {
timesTable = prompt(timesTable + " is not a " +
"valid number, please retry", -1);
I can't make this sample code to load properly in Google Chrome; it loads a blank page. What seems to be wrong with the code?
Code is below:
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<body>
<script type="text/javascript">
var myString = “56.02 degrees centigrade”;
var myInt;
var myFloat;
document.write(“\“” + myString + “\“ is “ + parseInt(myString) +
“ as an integer” + “<BR>”);
myInt = parseInt(myString);
document.write(“\“” + myString + “\“ when converted to an integer equals “ +
myInt + “<BR>”);
myFloat = parseFloat(myString); document.write(“\“” + myString +
“\“ when converted to a floating point number equals “ + myFloat);
</script>
</body>
</html>
Dave was absolutely right, it was the quotes. This version, with fixed quotes, loads in my Chrome.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<script type="text/javascript">
var myString = "56.02 degrees centigrade";
var myInt;
var myFloat;
document.write("\"" + myString + "\" is " + parseInt(myString) +
" as an integer" + "<BR>");
myInt = parseInt(myString);
document.write("\"" + myString + "\" when converted to an integer equals " +
myInt + "<BR>");
myFloat = parseFloat(myString); document.write("\"" + myString +
"\" when converted to a floating point number equals " + myFloat);
</script>
</body>
</html>
Here's what I'm seeing: