problem with console command, the content can not print anything? - javascript

I am newbie with javascript and I wrote a very simple program to display something using console command like this
function dogYears(dogName, age) {
var years = age * 7;
console.log(dogName + " is " + years + " years old");
}
var myDog = "Fido";
dogYears(myDog, 4);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Exercise2</title>
</head>
<body>
</body>
</html>
As you can see, I hope that I made the function and then, use var to assigned the value myDog to Fido, and then I want to use the function dogYears to print by the command console.log.
But when I ran the file .html (I saved it by .html), it did not display anything.
What error did I get in this case ? Could you please help me in this one ? Thank you very much for your help.

To display your result in browser's console just add your JavaScript logic inside script tag in your html file before closing body tag or create separate JavaScript file and import it using script tag
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Exercise2</title>
</head>
<body>
<script>
function dogYears(dogName, age) {
var years = age * 7;
console.log(dogName + " is " + years + " years old");
}
var myDog = "Fido";
dogYears(myDog, 4);
</script>
</body>
</html>

The problem is that you are not viewing the console. The console is not on the webpage, but instead on a separate tab. Press F12 on the keyboard, or press Ctrl+Shift+i and then click on the console. There is nothing wrong with the code. But if you want a more protected function, you can use this JavaScript code.
<script>
function dogYears(dogName, age) {
if(typeof(dogName)==="string"&&typeof(age)==="number"){
var years = age * 7;
console.log(dogName + " is " + years.toString() + " years old");
}else{
console.log("Error you want to display");
}
}
</script>

If you want to display information on the browser, typed document.write instead of console.log
<script>
function dogYears(dogName, age) {
var years = age * 7;
document.write(dogName + " is " + years + " years old");
}
var myDog = "Fido";
dogYears(myDog, 4);
</script>

Related

Why my website contents disappear till Prompt method finalized?

I have read that placing script tag at the bottom will solve such issue of disappearing contents of the webpage till JS runs but I am still facing such issue and I don't know what is the reason behind that?
Example of my issue
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Script Demo</title>
</head>
<body>
<h1>First exercise</h1>
<p>Test 3 Built-in JS Methods</p>
<script src="script.js"></script>
</body>
</html>
JS Code:
var firstName = prompt("What is your first name?");
var lastName = prompt("What is your last name?");
var age = prompt("What is your age?");
var fullName = firstName +" " + lastName
console.log("Your full name is " + fullName);
console.log("You are " + age + " years old");

Javascript prompt command executes before the documents writes

I have a problem with the code below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/main.css">
<title>The Ultimate Quiz Challenge</title>
</head>
<body>
<div class="container">
<h1>The Ultimate Quiz Challenge</h1>
<script>
document.write("<h3> " + "Welcome to the ultimate quizz challenge" +"</h3>");
document.write("<p> "+"Hi I will ask you five questions and then rank you" + "</p>");
var question1 ="<p>What is the capital of England</p>";
var firstanswer ="London";
var question2 = "<p>How many sides are there to a square</p>";
var secondanswer = 4;
var noofquestions = 2;
var count = 1
/*var temp = eval('question' +1); */
/*document.write(temp);*/
/* main loop asking questions */
while (count <= 2) {
var temp = eval('question' + count);
document.write(temp);
var answer = prompt("Please type your answer ");
count++;
}
</script>
</div>
</body>
</html>
When I load the file into a browser such a chrome or safari it does not execute as hoped.
In short the document.write commands do not come out onto the screen until the prompt window as asked for two inputs. I thought the first thing to be seen would be the Ultimate Quiz Challenge followed by the commands in the open script tag down to the bottom ?
You should use the onload event on your body, so your script executes once the html page is rendered. It should work with :
<body onload="displayText()">
displayText() being a function you define in your script :
var displayText = function () {
while (count <= 2) {
var temp = eval('question' + count);
document.write(temp);
var answer = prompt("Please type your answer ");
count++;
}
};
or something similar.

Why is my output repeating?

I want to alert "running function cannons" then when I press ok I want it just to say "cannon ship sails off to 14 degrees" but it keeps printing the alert within my output.
JS
function alertMessage (message) {
alert (message);
}
alertMessage("the Battle has begun");
function alertShip (ship, number) {
alert (ship);
document.write (ship + "the ship sails off to " + number + "degrees");
}
alertShip("running function cannons", 14);
HTML
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Functions</title>
<!-- This links to the js code specific for this page -->
<script src="functions.js"></script>
</head>
<body>
<div id="output"> </div>
<div id="output2"> </div>
</body>
</html>
Try removing the ship parameter from the document.write and replacing the statement with this:
document.write("cannon ship sails off to " + number + " degrees");
Then, you should be able to get your desired output.
*p.s.: if you're doing this on a text editor and trying to run this on a browser, you can consider changing the tag to this: .
I hope this helps!
don't give them the same variable to output .. alert (ship) then document.write (ship+.....).
Try this instead
function alertShip (ship, number) {
alert (ship);
document.write ("Cannon ship sails off to " + number + "degrees");

How to make the output of multiple JavaScript functions display in HTML?

So I'm trying to display the results of a few function calls in a JavaScript file that uses benchmark.js in a separate HTML file.
My js file looks something like this (disregard the names of methods and classes):
class.init(function(context) {
Benchmark("function description", {
'defer': true,
fn': function(deferred) {
var x = context.ones([100, 100]);
var y = x.repeat(2, 0);
context.barrier(function (){
deferred.resolve();
});
},
'onComplete': function(event) {
//This is what I'd like to print out
console.log(this.name + ": " + (this.stats.mean * 1000).toFixed(2) + " ms");
//
}
}).run();
There are multiple function calls similar to this.
My HTML just looks something lile:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title> Sublime Webpage </title>
</head>
<body>
<div class="main">
<div class="head">
<h1>Hello</h1>
</div>
<script src="filename.js"></script>
</div>
</body>
</html>
At the moment, it just prints the results to the console, which is better than nothing, but obviously not what I want. I talked to someone briefly and they suggested I use jQuery. I looked into it, and tried using document.write(this.name + ": " + (this.stats.mean * 1000).toFixed(2) + " ms") in the place of console.log(), but this didn't seem to work. Does anyone have suggestions?
Use document.createTextNode:
// add an output div to your html
<div id='output'></div>
// in your benchmark code
var output = document.getElementById('output');
output.appendChild(document.createTextNode('some result'));
Fiddle

Javascript array variables not behave equally

Javascript code reads XML local file into array variable arrTst. It works in Firefox 25.0.1 and I can see arrTst values in debugger. I have problems working with this arrTst. Example is displaying alert.
If I swap alert lines (displaying arrTest first) then alerts are not displayed.
Can anyone explain why alerts are not displayed when lines are swapped ?
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<inData>
<record>
<date>2012-08-01</date>
<amount>7</amount>
</record>
<record>
<date>2012-08-02</date>
<amount>22</amount>
</record>
</inData>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<script type="text/javascript" src="jquery-1.10.2.js"> </script>
<title>test read XML file</title>
</head>
<body>
<h1 >Test XML</h1>
<div id="TstMsgArea"></div>
<script type="text/javascript">
var str1="";
var arrTst=[];
var arrCon=[["2013-08-01", 1], ["2013-08-02",33]];
$(document).ready(function(){
/*******************************************************************
* read xml file from local filesystem & push to array
*******************************************************************/
$.get("test.xml",{},function(xml){
$('record',xml).each(function(i) {
_date = $(this).find("date").text();
_amount = parseInt($(this).find("amount").text());
var X0=[];
X0.push(_date);
X0.push(_amount);
arrTst.push(X0);
alert (str1);
str1+=_date +", "+_amount+"; ";
$("#TstMsgArea").append(str1);
});
});
/*******************************************************************
* check array values - if lines swapped no go !
*******************************************************************/
alert ("arrConst : " + arrCon[0][0]+", " + arrCon[0][1]+"; " + arrCon[1][0]+", " + arrCon[1][1]);
alert ("arrTest : " + arrTst[0][0]+", " + arrTst[0][1]+"; " + arrTst[1][0]+", " + arrTst[1][1]);
}); //$(document).ready
</script>
</body>
</html>
Your alerts are in the wrong place. You need to put them inside your success function, or in another function that you call from within that function.
Also, you shouldn't declaring str1 and arrTst outside the success function. Those are values you are building up inside that function, and they won't be available outside of it.
If you want to use those variables somewhere else in your code, you need to put the code that uses them inside a function somewhere. Call that function from inside your $.get() success function, and pass it the variables as an argument. Then you can be sure that the data is ready.
var arrCon=[["2013-08-01", 1], ["2013-08-02",33]];
$(document).ready(function(){
/*******************************************************************
* read xml file from local filesystem & push to array
*******************************************************************/
$.get("test.xml",{},function(xml){
var str1="";
var arrTst=[];
$('record',xml).each(function(i) {
_date = $(this).find("date").text();
_amount = parseInt($(this).find("amount").text());
var X0=[];
X0.push(_date);
X0.push(_amount);
arrTst.push(X0);
alert (str1);
str1+=_date +", "+_amount+"; ";
$("#TstMsgArea").append(str1);
});
alert ("arrConst : " + arrCon[0][0]+", " + arrCon[0][1]+"; " + arrCon[1][0]+", " + arrCon[1][1]);
alert ("arrTest : " + arrTst[0][0]+", " + arrTst[0][1]+"; " + arrTst[1][0]+", " + arrTst[1][1]);
});
}); //$(document).ready

Categories