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
Related
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>
I have a button on previous page which redirects to this page but the problem is when the page loads it doesn't show the confirm box. I get this error
Uncaught RangeError: Maximum call stack size exceeded
The code for the page:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
//script
<script type="text/javascript">
function confirm(){
var con = confirm("Are You Sure?");
if(con = true){
window.location = "delete.php";
}
else{
history.go(-1);
}
}
</script>
<body onload="confirm()">
</body>
</html>
You have two issues in your javascript code:
You have named your function to be the same as the reserved function you are trying to call.
Your comparison is actually an assign
To fix the first problem, simply change the name of your function to something else like confirmDeletion()
<script>function confirmDeletion() { /* do stuff */ }</script>
<body onload="confirmDeletion()">
To fix the second problem, change the comparison. In javascript, the if statement automatically coerces the input into a boolean, meaning you don't actually need to compare it to true.
if (con) {
/* do confirmed true stuff */
} else {
/* do confirmed false stuff */
}
For future reference, make sure to always use triple equal === sign for comparison, otherwise you will get unexpected behavior.
You're always going to go back 1 page because you are not evaluating your condition correctly.
if (con = true) {
window.location = "delete.php";
}
Should be
if (con == true) {
window.location = "delete.php";
}
Note the additional =, = is an assignment operator and == is used to compare and evaluate the condition.
Try renaming your function from confirm to something else. The problem is that you're going into an infinite loop by calling confirm inside your confirm function.
So for example, this would work as I've renamed confirm to myConfirm:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
//script
<script type="text/javascript">
function myConfirm(){
var con = confirm("Are You Sure?");
if(con = true){
window.location = "delete.php";
}
else{
history.go(-1);
}
}
</script>
<body onload="myConfirm()">
</body>
Edit
Also change con = true to con == true to check if con is true rather than assigning it the value true.
Change the name of the function. The condition, if(con = true)is assigning truthy value to con You should be comparing for truthy value like if(con). You should be doing,
<script type="text/javascript">
function confirmNavigation(){
var con = confirm("Are You Sure?");
if(con){
window.location = "delete.php";
}
else{
history.go(-1);
}
}
</script>
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;
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.
Below is my html page:
<html>
<head>
<title>My Cat website</title>
</head>
<script type="text/javascript" src="script12.js"></script>
<body>
<h1>
My_first_cat_website
</h1>
</body>
</html>
Below is my JavaScript:
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
alert(ans);
if(ans<10)
{
alert(ans);
}
var newans=ans.subString(0,9)+"...";
}
Here my code is not going into if block. My requirement is if var "ans" length is above 10 then append it with ... else throw an alert directly. Can anyone help me?
Here is Solution using data property
window.onload=initall;
function initall()
{
var ans=document.getElementsByTagName('a')[0].firstChild.data;
if(ans.length<10)
{
alert("hmmm.. its less then 10!");
}
var newans= ans.substring(0,9)+"...";
document.getElementsByTagName('a')[0].firstChild.data = newans;
}
Here is it live view you wise to check example: http://jsbin.com/obeleh
I have never heard of the data property on a DOM element. Thanks to you, I learned it's a property on textNode elements (the same as nodeValue).
Also, using getElementsByTagName when the ID is available is unperformant.
subString doesn't work, it is substring. The case is important for methods as javascript is case sensitive (like most programming languages).
The other thing you're missing is an else. In your code, the var newans... will always be ran.
Here is something working:
window.onload = function() {
var ans = document.getElementById( 'message' ).textContent;
if ( ans.length < 10 ) {
alert( ans );
}
else {
var newans = ans.substring( 0, 9 ) + '...';
}
}