Trouble getting my basic switch program to execute - javascript

I'm a beginner programmer, and I'm sure the answer is staring me in the face, but I cannot figure out what I am doing wrong. It's just a simple program that lets the user input one of three types of weather, and depending what is entered into the text field, the program will answer with the appropriate type of footwear. I have been poring over it for hours, tweaking here and there, but I can't get it to work. Any ideas? Here is the code:
<!DOCTYPE html>
<html lang="en-us">
<head>
<title>What Shoes Should I Wear?</title>
<script type="text/javascript">
function shoeWeather() {
var shoe;
switch (weather) {
case 'hot':
shoe = "sandals";
break;
case 'rain':
shoe = "galoshes";
break;
case 'snow':
shoe = "boots";
break;
default:
shoe = "shoes";
break;
return;
document.getElementById('shoe').innerHTML = shoes;
}
}
</script>
</head>
<body>
Weather:<input type="text" id="weather">
<button type="button" onclick="shoeWeather()">What's the Right Shoe for the Job?</button>
<div id="shoe"></div>
</body>
</html>

the variable weather, that you are trying to operate your switch statement on, isn't defined. You will have to read the value of your input and then operate the switch on that.
you are putting your document.getElementById('shoe').innerHTML = shoes; inside the switch, before a return statement and use a mistyped variable (shoes should be shoe).
Try something like this:
try:
var shoe='';
switch (document.getElementById('weather').value){
//set shoe based on switch cases
}
document.getElementById('shoe').innerHTML = shoe;

Related

printing output in the same window html and javascript

Below is the code I have written. Every button I press takes me to a new window where another there is another button that is to be pushed by the user. When that button is pushed, an alphabet is printed out. Every alphabet opens to a new page. This setting is not very user friendly and I am trying to get the output on the same window.
Here is the code I have written for the main page:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Alphabets</title>
<script>
function alphabet(alpha){
switch(alpha){
case 1:
window.open("alphabetI.html");
break;
case 2:
window.open("alphabetSS.html");
break;
case 3:
window.open("alphabetH.html");
break;
case 4:
window.open("alphabetA.html");
break;
}
}
</script>
</head>
<body>
<h2>I'm Isha</h2>
<h3> Press either of these buttons to see the output</h3>
<button onclick = "alphabet(1)" >Button-1</button>
<button onclick = "alphabet(2)" >Button-2</button>
<button onclick = "alphabet(3)" >Button-3</button>
<button onclick = "alphabet(4)" >Button-4</button>
</body>
</html>
Here is the code I have written for Alphabet I which is written on "alphabetI.html":
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Alphabet:I</title>
<script>
function here(){
var a;
while(a != 14){
for(a = 0 ; a < 4 ; a++){
document.write("* ");
}
document.write("<br>");
for( a = 4; a < 10 ; a++) {
document.write(" * ");
document.write("<br>");
}
for( a = 10 ; a < 14 ; a++) {
document.write("* ");
}
}
}
</script>
</head>
<body>
<h2><u>I</u>SHA</h2>
<button onclick = "here()" >Alphabet I</button>
</body>
</html>
Codes for other alphabets are similar and include for loops.
I tried using window.alert() as it opens the alert box on the same page thus making it convenient, but that does not give me the desired output when placed in a for loop. For instance, if my loop runs 3 times, it will give me the alert message 3 times rather than printing the asterisks three times in one alert message.
Then I tried console.log, but I realized that it prints a message to the web console, so it would not be of any use. I also tried using document.getElementbyId(); but again, that would not work in a for loop as the id of the place I am printing it to is just being replaced by my new value, thus, it would not print more than one element or value from a for loop.
I finally used document.write() which works in every way but when a button is clicked, the output is printed on the same page and replaces the other buttons. That way, the user can neither press another button because the buttons are replaced by the generated alphabet, nor can the user go back.
Eventually I created more html files and pasted my code to create the letters using for loops there, then I used window.open() to open a new window displaying the code. However, this is not very user friendly, and I would like for output to be displayed on the same page, underneath the buttons.
You can create a div on the screen and give it an ID. Then refer to that Div and add content via innerHTML. In your buttons onclick, you can refer to each function too, no need for a switch.
This is a quick example. The key to reusing an element is adding content for example using += instead of replacing it with =
const output = document.querySelector("#output")
function alpha1() {
output.innerHTML = "";
var a;
while (a != 14) {
for (a = 0; a < 4; a++) {
output.innerHTML += "* ";
}
output.innerHTML += "<br>";
for (a = 4; a < 10; a++) {
output.innerHTML += " * ";
output.innerHTML += "<br>";
}
for (a = 10; a < 14; a++) {
output.innerHTML += "* ";
}
}
}
function alpha2() {output.innerHTML = "2";}
function alpha3() {output.innerHTML = "3";}
function alpha4() {output.innerHTML = "4";}
<h2>I'm Isha</h2>
<h3> Press either of these buttons to see the output</h3>
<button onclick="alpha1()">Button-1</button>
<button onclick="alpha2()">Button-2</button>
<button onclick="alpha3()">Button-3</button>
<button onclick="alpha4()">Button-4</button>
<div id="output"></div>
use JQuery to make the process easy
add JQuery CDN in the head section
<script
src="https://code.jquery.com/jquery-3.6.3.min.js"
integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU="
crossorigin="anonymous"></script>
create a div with id="container"
then use load() function of Jquery
function alphabet(alpha) {
switch (alpha) {
case 1:
$("#container").load("alphabetI.html");
break;
like this
here is the complete code
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta name="viewport" content="width=device-width">
<meta charset="utf-8">
<title>Alphabets</title>
<script
src="https://code.jquery.com/jquery-3.6.3.min.js"
integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU="
crossorigin="anonymous"></script>
</head>
<body>
<h2>I'm Isha</h2>
<h3> Press either of these buttons to see the output</h3>
<button onclick="alphabet(1)">Button-1</button>
<button onclick="alphabet(2)">Button-2</button>
<button onclick="alphabet(3)">Button-3</button>
<button onclick="alphabet(4)">Button-4</button>
<div id="container"></div>
<script>
function alphabet(alpha) {
switch (alpha) {
case 1:
$("#container").load("alphabetI.html");
break;
case 2:
window.open("alphabetSS.html");
break;
case 3:
window.open("alphabetH.html");
break;
case 4:
window.open("alphabetA.html");
break;
}
}
</script>
</body>
</html>
i hope it will help you !!..

Javascript if statement issue: No display in the webpage

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>

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.

JS function does not update HTML string

Im pretty new to JS and HTML (started ~20 hours ago) and already have a problem: below you can see my code. As one tutorial said, clicking on button will change the statusLine text. But something went wrong and i cant figure it out.
<!DOCTYPE html>
<html>
<head>
<title>Некое подземелье</title>
</head>
<body>
<p id="statusLine">Вы попали в подземелье.</p>
<button type="button" onclick="goDeeper()">Идти глубже в подземелье</button>
<script>
function goDeeper()
{
var nextEvent=(Math.floor(Math.random()*10+1));
switch(nextEvent){
case'1':
document.getElementById("statusLine").innerHTML="Вам на пути попался гоблин!";
break;
}
}
</script>
</body>
</html>
So, something is wrong. What should i do in order to fix this?
Try making the case statement match the number 1 rather than the string '1':
function goDeeper()
{
var nextEvent = Math.floor(Math.random()*10+1);
switch(nextEvent) {
case 1:
document.getElementById("statusLine").innerHTML="Вам на пути попался гоблин!";
break;
}
}
Or for that matter, if there is only one condition you need to match, just get rid of the switch and use a simple if block:
function goDeeper()
{
var nextEvent = Math.floor(Math.random()*10+1);
if (nextEvent == 1) {
document.getElementById("statusLine").innerHTML="Вам на пути попался гоблин!";
}
}
What I understand you want to change the text on click button so Try this
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
document.getElementById("demo").innerHTML="Hello World";
}
</script>
</head>
<body>
<p>Click the button to trigger a function.</p>
<button onclick="myFunction()">Click me</button>
<p id="demo"></p>`enter code here`
</body>
</html>
Refrence Link : http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick

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