Javascript if statement issue: No display in the webpage - javascript

I have a VERY BASIC knowledge of javascript and I was looking forward to learn some conditional statement in javascript. So I went on and entered this code in a HTML file called "index.html":
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>
And the result that came was completely normal. A title called "Sample Webpage" appeared.
But the next code what I entered created problems in the result,
var myNumber = window.prompt("Enter number: ");
parseFloat(myNumber);
document.write(myNumber);
The result comes as expected.
if (myNumber > 15) {
document.write(<p>Good! You've passed! </p>);
}
else {
document.write(<p>You failed! Try again next time.</p>);
}
But when I add this if statement which gives an output based on the user's input, I get a blank page. I don't understand what is the reason for this. Are there any problems in the syntax?
It also seems to me that it doesn't execute the first part of the code I've written, it completely wants all of the code. I feel this is normal but doesn't it have to actually execute the "document.write" code?

Way I see it, you need to quote your strings in document.write(string).
like this:
if (myNumber > 15) {
document.write("<p>Good! You've passed! </p>");
}
else {
document.write("<p>You failed! Try again next time.</p>");
}
I hope it is useful for you. Thank you.

document.write takes a string as argument. You pass it HTML.
Just change
document.write(<p>Good! You've passed! </p>);
to
document.write('<p>Good! You've passed! </p>');
to make it work. A better approach is to add
<p id="message"></p>
to the page and where you have
document.write('<p>Good! You've passed! </p>');
you can use
document.getElementById('message').textContent='Good! You've passed!';
document.getElementById("myButton").addEventListener('click', function() { // when clicked
let myNumber = window.prompt("Enter number: ");
myNumber = parseFloat(myNumber); // convert to number from string
document.getElementById('number').textContent = myNumber;
const msg = document.getElementById('number'); // output container
if (myNumber > 15) {
msg.textContent = 'Good! You\'ve passed!' // escaping the quote
}
else {
msg.textContent = 'You failed! Try again next time.';
}
});
// above can be written using a so called ternary:
// msg.textContent = myNumber > 15 ? 'Good! You\'ve passed!' : 'You failed! Try again next time.'
<!DOCTYPE html>
<html>
<head>
<title>A sample webpage</title>
</head>
<body>
<p id="number"></p>
<p id="message"></p>
<button type="button" id="myButton">Did you pass?</button>
<script src="script.js"></script>
</body>
</html>

Related

Trying to make a notepad like script in HTML/JS

Edit: Just confirming: I want what the user typed to be saved so that when he reloads/leaves the webpage and comes back what he wrote earlier is still there.
I tried using cookies but it only put one line of Default(variable) when I reloaded the page. Im trying to get it to work with localStorage now but it sets the textarea to "[object HTMLTextAreaElement]" or blank when I reload. I read that this error can be caused by forgetting to add the .value after getElementById() but I did not make this mistake. I am hosting and testing the webpage on Github(pages). What am I doing wrong? here is the code(ignore the comments also it might not work in jsfiddle bc it localstorage didn't work there for me):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>le epic web page</title>
</head>
<body><!--
= "\n"-->
<textarea id="txt" rows="4" cols="50" oninput="save();"></textarea>
<script>
var Default="P1 Homework: \nP2 Homework: \nP3 Homework: \nP4 Homework: \n";
if(localStorage.getItem("P") == ""){
document.getElementById("txt").value=Default;
localStorage.setItem("P")=Default;
}else{
document.getElementById("txt").value=localStorage.getItem("P");
}
//update cookie (called when typed)
function save(){
var txt=document.getElementById("txt").value;
//txt=txt.replace(/\r\n|\r|\n/g,"</br>");
localStorage.setItem("P",txt);//set cookie to innerHTML of textArea, expires in 1 day
}
//when page closed/reloaded
window.onbeforeunload = function(){
localStorage.setItem("P",txt);//update cookie when page is closed https://stackoverflow.com/a/13443562
}
</script>
</body>
</html>
When you are exiting the page, you are referencing the text element and storing that in localstorage. Since localStorage is a string it converts the html element reference into the text you see.
window.onbeforeunload = function(){
localStorage.setItem("P",txt);
}
You are doing it correctly with save, so just call save with the beforeunload event
window.addEventListener('beforeunload', save);
Another bug in the code is the line
if(localStorage.getItem("P") == ""){
when localStorage is not set, it returns null. So the check would need to be a truthy check ( or you can check for nullv)
if(!localStorage.getItem("P")){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>le epic web page</title>
</head>
<body>
<textarea id="txt" rows="4" cols="50" oninput="save();"></textarea>
</body>
<script>
const Default =
"P1 Homework: \nP2 Homework: \nP3 Homework: \nP4 Homework: \n";
if (
localStorage.getItem("P") === "" ||
localStorage.getItem("P") === null ||
localStorage.getItem("P") === undefined
) {
localStorage.setItem("P", Default);
} else {
let currentValue = document.getElementById("txt");
currentValue.value = localStorage.getItem("P");
}
function save() {
let txt = document.getElementById("txt").value;
localStorage.setItem("P", txt);
}
window.onbeforeunload = function () {
let txt = document.getElementById("txt").value;
localStorage.setItem("P", txt);
};
</script>
</html>

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

Basic HTML Function Call with buttons

I'm trying to learn basic HTML and Javascript, and am not sure what is wrong with this code. It is probably a very simple error and I'm sorry if it is. When I try clicking the buttons, Chrome says in the console that "correct" and "incorrect" are not defined, but I have checked the syntax for the functions and I can't see what is wrong. Thanks for your help :)
<!DOCTYPE html>
<html>
<head>
<title>Question 1</title>
</head>
<body>
<p>Q1: What is the height of the Eiffel Tower?</p>
<br>
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!
<br>
Next Question";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!
<br>
Next Question";
}
</script>
<button onclick="incorrect()">767m</buttton>
<br>
<button onclick="incorrect()">442m</button>
<br>
<button onclick="correct()">324m</button>
<br>
<button onclick="incorrect()">278m</button>
<p id="feedback"></p>
</body>
You have confusing ""(double quotes) in the innerHTML strings. Try this:
instead of "q2.htm" use 'q2.htm'
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href='q2.htm'>Next Question</a>";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!<br><a href='q2.htm'>Next Question</a>";
}
</script>
If you look at the console log in Chrome (press F12 to enter Developer Tools where you can see the log), you will see an error message “Unexpected token ILLEGAL”. The reason is that you have line breaks inside a JavaScript string, which is not permitted, so the function definitions fail in parsing. Moreover, you are using quotes inside a quoted string, which isn’t permitted either. Use single quotes (') as inner quotes or (in this case) just omit them, e.g.
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href=q2.htm>Next Question</a>";
}
This works:
<script>
function incorrect()
{
document.getElementById("feedback").innerHTML =
"incorrect!<br><a href='q2.htm'>Next Question</a>";
}
function correct()
{
document.getElementById("feedback").innerHTML =
"Correct!<br><a href='q2.htm'>Next Question</a>";
}
</script>
You have to put them on the same line or use concatenation.

Issues with my JS?

I wrote a little script to generate a random yes or no. However, it is not running. At all. What is wrong with my code?
Here is a JSFiddle: http://jsfiddle.net/u8ukp/
My code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Should You? | A completely random decision</title>
<script type="text/javascript">
function func(){
var i = Math.random();
if (i >= 0.5) {
var e = document.getElementById('result');
e.InnerHTML = "Yes! :)";
}else{
var e = document.getElementById('result');
e.InnerHTML = "Nope! :("
};
};
</script>
</head>
<body>
<header>Should You?</header>
<br><br>
<a onclick="func();">Should You?</a>
<br><br>
<span id="result"></span>
</body>
</html>
Thanks!
innerHTML, not InnerHTML -- Javascript is case-sensitive.
Here's a working JSBin
It is a number of things actually. First innerHTML and not InnerHTML.
Second, not use <span> but <div>, and last, at the fiddle 'onLoad' was selected, making it impossible to debug.

innerHTML failing on case

I am making a interactive application with a text field to practice javascript, but I am finding for validation, that the case does not display innerHTML text though the rest of the function loops though. text.innerHTML works in all other cases, am I missing something here?
Javascript
function getNum(input){
if (isNaN(input)) {
oldstate = state-1;
state = 33;
console.log("Loading error Message...");
act();
}
else{return(parseInt(input, 10));}
}
function act(){
console.log("Case: "+state);
input = inputf.value;
inputf.value="";
switch(state){
case 0:
name = input;
text.innerHTML = "Well, hello there, "+name+"! Nice to meet you. What's your age?";
break;
case 1:
text.innerHTML = "Loading...";
age = getNum(input);
text.innerHTML = "So, "+name+" you are "+age+" years old!";
break;
case 33:
text.innerHTML = "That is NOT a number! Hit Submit to Return.";
console.log("Error Successfully loaded!");
state = oldstate;
break;
}
state=+1;
}
function getStr(input){
}
Here is my HTML with the text field id's. Any optimization suggestions would also be appreciated.
HTML
<!DOCTYPE html>
<html>
<head>
<title>titles are lame</title>
<link/>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script type="text/javascript" src="script.js"></script>
<script></script>
</head>
<body>
<div id="wrapper"><div id="text">First, let's have your name.</div>
<br>
<input type='text' id="input"><input type="submit"id="submit" onclick="act()">
</div>
<script>
var state = 0;
var inputf = document.getElementById("input");
var text = document.getElementById('text');
var input, name, age,oldstate;
document.getElementById("input").addEventListener("keydown", function(e) {
// Enter is pressed
if (e.keyCode == 13) { act(); }
}, false);
</script>
</body>
</html>
I think I know what the problem is. In case 1, you call the getNum method, it executes just fine in the correct case, calls the act() method, enters case 33 correctly, returning an error and... then keeps executing case 1. Because you didn't specify a return statement in the first case of the getNum function, age has an undefined value. It should work fine if you add this line:
if (!age) return;
just after calling the getNum method in case 1.
EDIT: I just realized you should also check how state is managed after detecting an error. Adding the line I gave you will leave a state of 33.
Click here to see the answer..
act() //Changed

Categories