why doesn't javascript print new row with \n? - javascript

I have a problem with JS, whenever I write "\n" while in script tag, it doesn't print new row.I am new to Javascript so can someone explain to me what is the problem?
Here is the code from my excercise:
<html>
<head>
<meta charset="utf-8">
<script>
var output;
var number = window.prompt("Enter mobile no: \n");
if( number>10000000 && number<99999999){
var ps = parseInt(number/1000000);
var vs = parseInt((number/1000)%1000);
var ts = number%1000;
output = "0" + ps + "/" + vs + "-" + ts +" ";
document.write("Mobile no. is : " + output + " " + "\n");
if( ps == 70 || ps == 71 || ps == 72 ){
document.write("Mobile no. is T-Mobile " + "\n");
}
if( ps == 75 || ps == 76){
document.write("Mobile no. is One " + "\n");
}
if( ps == 77 || ps == 78){
document.write("Mobile no. is Vip " + "\n");
}
}
</script>
</head>
<body>
//not important
</body>
</html>

You're outputting to the browser, so HTML is relevant, not plain text. Just replace the "\n" with "<br>".

You are writing HTML to the page. It does not recognize new lines. You need to use the "<br>" tag.

If you are writing in a .html file use <br> tag like this:
document.write("<br>");
Otherwise, you can use "\n".

Related

How can I assign a javascript variable in html format?

For example, there is a page like below.
<html>
<head>
<title>Variables!!!</title>
<script type="text/javascript">
var lookatthis = 11;
var one = 22;
var two = 3;
var add = one + two;
var minus = one - two;
var multiply = one * two;
var divide = one/two;
document.write("First No: = " + one + "<br />Second No: = " + two + " <br />");
document.write(one + " + " + two + " = " + add + "<br/>");
document.write(one + " - " + two + " = " + minus + "<br/>");
document.write(one + " * " + two + " = " + multiply + "<br/>");
document.write(one + " / " + two + " = " + divide + "<br/>");
</script>
</head>
<body>
</body>
</html>
I want to assign the javascript variable "lookatthis" on debug console.
//apologise for my ambiguous question. I would rather say,
"I want to assign new value to variable "lookatthis" on this web-page using console on explorer."
Thank you for your kind teaching.)
Open debug console and write there:
lookatthis = 20
But this get you nothing
You can use the log method:
console.log(lookatthis);
Anywhere in your script block after your initial assignment of lookatthis, you can write the value to the console with the command:
console.log(lookatthis);
You achieve it by using prompt function
var lookatthis = prompt('Type the lokaltthis value');
If what you want is to be able to 'set' the value of lookatthis, you can use an input and using jquery or pure js get the value of the input and assign it to 'lookatthis'.
Edit: You can also use in the chrome console: lookatthis=25
but as your script loads when page loads, changes will not be shown but the value will be changed

why javascript link not work in local host?

PLEASE help js file does not work in localhost, when script tag in head.
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="javascript/script.js"></script>
</head>
<body>
<p id="demo"></p>
</body>
</html>
but when it in body it works.My question .why?
The problem is that your code is executed in head before the body loaded. document.getElementById("demo") won't find the element "demo" because it does not exist yet.
Use it on onload:
window.onload = function() {
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34};
}
document.getElementById("demo") will try to find an element with id demo but since the page hasn't been rendered completely yet , it won't find anything and return null.
use window.onload.
window.onload = function(){
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34};
};
The scripts should always be loaded at the bottom of your body, to be sure that DOM is loaded before execution. Alternatively you can use JQuery $(document).ready(function(){ //put your code in here });
This is because when your are putting this js snippet inside head tag it does not know what is <p id="demo"></p>
But when you put it inside body tag, first DOM get parsed then js is executed. You can still put it inside head tag by using window.load.Here is snippet
window.onload=function(){
document.getElementById("demo").innerHTML =
typeof "john" + "<br>" +
typeof 3.14 + "<br>" +
typeof false + "<br>" +
typeof [1,2,3,4] + "<br>" +
typeof {name:'john', age:34};
}
WORKING COPY

JavaScript beginner variable confusion

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);

Text is going up/down? Not across. Javascript Loop.

<html>
<body>
<script>
var namIn = window.prompt("Enter Senator’s State and FULL Name, separated by space:" );
var namAr = namIn.split("");
var namArLen = namAr.length;
document.write( namAr + "<br>" + "Length:" + namArLen);
var i;
for (i = namArLen-1; i >=0;i--)
{var result = document.write("<br>" + "<h1>" + namAr[i] + "</h1>" ); }
</script>
</body>
</html>
I used a loop to help reverse my text (done for an into to JS assginment) but the letters are going in a straight line up and down. Like:
O
L
L
E
H
(It's supposed to be a senator's name, but "hello" will do for an example)
Why is this and how can I make it look normal?
You can make it look normal by putting the letters into another variable and then writing that variable out all at once. Look at lines 6, 9 and 11 in this (tested) solution.
<script>
var namIn = window.prompt("Enter Senator’s State and FULL Name, separated by space:" );
var namAr = namIn.split("");
var namArLen = namAr.length;
document.write( namAr + "<br>" + "Length:" + namArLen);
var result = '';
var i;
for (i = namArLen-1; i >=0;i--) {
result = result + namAr[i];
}
document.write("<br>" + "<h1>" + result + "</h1>" );
</script>
Maybe, you should add one css rule, for example:
h1 {display: inline-block;}
And remove all of BR tags.
You are using H1 tags which create new lines
{var result = document.write( namAr[i] ); }
use a style to increase the font size
example:
http://jsfiddle.net/sanpopo/rk6Nk/

Error when calling JavaScript function — "can't find variable"

I'm attempting to complete and exercise from the JavaScript Bible, and am having trouble getting my script to function.
The assignment is to create a page that allows users to query a planet's name, and, via a script that matches the planet's name with its data stored in the associate arrays, call up its distance and diameter information.
I'm attempting to call the function 'getPlanetInfo' via a button (onclick='getPlanetInfo()'). However, my error console reports that it cannot find a variable named 'getPlanetInfo' when I attempt to run it.
I've attached both my JS and HTML code below. Any idea as to why my function isn't being properly called would be hugely appreciated.
HTML:
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript" src="planets.js"></script>
</head>
<body>
<h1>Check a planet's distance from the sun and its diameter!</h1>
<form>
<input type="text" name="entry" id="entry">
<input type="button" value="Check it!" onClick="getPlanetInfo()">
</form>
</body>
</html>
JS:
var planetNames = new Array(4);
planetNames[0] = "Mercury";
planetNames[1] = "Venus";
planetNames[2] = "Earth";
planetNames[3] = "Mars";
var planetDistances = new Array(4);
planetDistances[0] = "36 million miles";
planetDistances[1] = "67 million miles";
planetDistances[2] = "93 million miles";
planetDistances[3] = "141 million miles";
var planetDiameters = new Array(4);
planetDiameters[0] = "3,100 miles";
planetDiameters[1] = "7,700 miles";
planetDiameters[2] = "7,920 miles";
planetDiameters[3] = "4,200 miles";
function getPlanetInfo()
{
var selectedPlanet = document.getElementById("entry").value;
for (var i = 0; i < planetNames.length; i++)
{
if (planetNames[i] == selectedPlanet)
{
break;
}
}
if (i < planetNames.length)
{
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
}
else
{
alert("Sorry, " + selectedPlanet + " isn't in the database.");
}
}
This line:
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
is missing a + sign after planetDistances[i], so the function has a syntax error and is not created, and naturally it's not found when called.
http://www.jsfiddle.net helps you create a reproducible case that we can all see, use it when you need to ask js questions.
You're missing a + - this:
alert(selectedPlanet + " is " + planetDistances[i] " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
should be
alert(selectedPlanet + " is " + planetDistances[i] + " in distance from the Sun and " + planetDiameters[i] + "in diameter.")
You should use something like Firebug to catch syntax errors when loading your script.

Categories