I understand that each if statement and each if else statement is contained inside curly braces. That's what I've done here so far. I just started this code and I tested it with only 20% done so that I can fix errors before the code get's too long. With everything looking correct I'm getting a syntax error that for the life of me I can't see where it is. Any suggestions? Here is the code. And here is the link: stickFigure
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>The mysterious road</title>
</head>
<script type="text/javascript">
var curScene = 0
function changedScene(decision){
var message = "";
if(curScene==0) {
curScene=1;
message = "Let the games began!";
}
else if(curScene ==1){
if(decision==1){
curScene = 2;
message = "Looks like you're on the right road.";
}
else(curScene = 3);
message = "you're stading on a bridge overlooking a peaceful stream.";
}
document.getElementById("sceneimg"). src = "scene" + curScene + .png; //There's a syntax error here that I don't see!
alert(message);
}
</script>
<body>
<div style="margin-top:100px; text-align:center">
<p><img id="sceneimg" src="../sfa/scene0.png" alt="Stick Figure" /></p>
Enter here for a glorious adventure!
<input type="button" id="decision" value="1" onclick="curScene(1)" />
Enter this gate for the surpirse of your life!
<input type="button" id="decision" value="2" oonclick="curScene(2)" />
</div>
</body>
</html>
Look here
else(curScene = 3);
and you should be able to work it out.
for the first syntax error you are aware of add say double quoats around the ".png"
and you havent got got ant objects that support the method (no functions found) calling curScene(1) and your only function is changedScene() plus a typo with the oonclick.
and what fearofawhackplanet said.
stick with it, dont give up
Also, even though JavaScript allows it, you're missing a semicolon after your first script statement:
var curScene = 0
Be aware of such omissions. Even though it's not a syntax or semantics error here, this could get you into trouble elsewhere, such as (made up):
return // return undefined
val1 + val2;
Because you use semicolons every where else to terminate your statements, it's best to be consistent.
Related
StackOverflow,
I'm a NOOB learning slowly. I got some errors when trying to validate the following code in HTML 5 validator and don't know where the errors are:
<!DoctypeHTML>
<HTML>
<head>
<title> Javascript Programming!</title>
<script type = “text/javascript”>
<function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
If (myValue ==0) {
alert(‘please enter a real value in the box’);
Return;
}
Var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</head>
<body>
</body>
</html>
Errors: Error: Bad value “text/javascript” for attribute type on element script: Expected a token character but saw “ instead.
From line 5, column 2; to line 5, column 34
↩ ↩
Error: End of file seen when expecting text or an end tag.
At line 18, column 7
dy>↩
Error: Unclosed element script.
From line 5, column 2; to line 5, column 34
↩ ↩
Any feedback? Thanks guys and gals.
PreYvin
You are using typographical quotes - change these to regular quotes. (single and double)
Ok, you've got a whole lot of invalid code (HTML and JavaScript) here:
<!DoctypeHTML>
Should be (case doesn't matter):
<!DOCTYPE html>
This:
<script type = “text/javascript”>
contains typographically formatted quotes instead of non-formatted quotes, which is a problem, but you don't even need the type=text/javascript anyway, so you can just write:
<script>
function is not an HTML tag, so this:
<function substitute () {
should be:
function substitute() {
Next, you are using formatted quotes in your JavaScript:
var MyValue = document.getElementID (‘mytextbox’).value;
which should be unformatted, like this:
var MyValue = document.getElementID ('mytextbox').value;
HTML isn't case-sensitive, but JavaScript is, so this:
If (myValue ==0) {
needs to be this:
if (myValue == 0)
More quote problems here:
alert(‘please enter a real value in the box’);
Should be:
alert('please enter a real value in the box');
More case-sensitivity issues here:
Return;
Should be:
return;
More quote and case-sensitivity issues here:
Var myTitle = document.getElementbyID (‘title’)
Should be:
var myTitle = document.getElementbyID ('title');
Lastly, when your script is finished and it's time to return to HTML, you didn't close your script, so this:
}
</head>
Should be:
}
</script>
</head>
You can always validate your HTML at: http://validator.w3.org
And, you can validate your JavaScript at: http://www.jslint.com
You also have invalid JavaScript so this should be valid.
<!doctype html>
<HTML>
<head>
<title> Javascript Programming!</title>
<script>
function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
if (myValue ==0) {
alert(‘please enter a real value in the box’);
return;
}
var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
</body>
</html>
you have an extra < in your code. but you need to revisit your javascript as it has many problems the script tag is not closed.
<!DoctypeHTML>
<HTML>
<head>
<title> Javascript Programming!</title>
<script type = “text/javascript”>
function substitute () {
var MyValue = document.getElementID (‘mytextbox’).value;
If (myValue ==0) {
alert(‘please enter a real value in the box’);
Return;
}
Var myTitle = document.getElementbyID (‘title’)
myTitle.innerHTML = myValue;
}
</script>
</head>
<body>
</body>
</html>
Lots of basic syntax errors here.
<!DoctypeHTML> should be <!DOCTYPE html>
the first error you listed, (Bad value “text/javascript” for attribute type on element script: Expected a token character but saw “ instead.) is due to a funky double quote character: “ It should be " This probably originated from your text editor. What are you using? I like Sublime, but there are lots of options. The important thing is that you use a text editor designed for coding.
the next two errors are due to your script tag not being closed. Just add </script> at the end of the script.
Like I said, these are just simple syntax errors though. What you really need to learn here is how to look at those error messages and tell what's going on. Notice how the error messages reference a line number and column number? That's to tell you where the problem is. (Sometimes it can be off depending on the error, but worry about that later). Take a look at the line it's complaining about, read the error message, and you should be able to figure out what's wrong.
Close your <script> tag.
Remove < from <function
Use regular quotes instead of typographical
space between Doctype and html ie. <!doctype html>
Lastly, keywords should be all smallcase ie. if, return, var
Updated
<!doctype html>
<html>
<head>
<title> Javascript Programming!</title>
<script type = 'text/javascript'>
function substitute () {
var MyValue = document.getElementID ('mytextbox').value;
if (myValue == 0) {
alert('please enter a real value in the box');
return;
}
var myTitle = document.getElementbyID ('title')
myTitle.innerHTML = myValue;
}
</script>
</head>
<body></body>
</html>
This has been asked 100x before but after reading a lot of those posts I'm still not sure what I'm doing wrong. The script is only executed when you press the button (so the textbox should exist in the DOM by the time the code is executed), Visual Studio even lets me autocomplete the getElementByID argument to inputField. Yet somehow it doesn't get the element and 'null' is printed on my screen.
My code is:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<!-- input field + button, and an empty value field -->
<input type="text" id="inputField" value="" />
<input type="button" onclick="printType()" />
</body>
<script>
function printType() {
console.log(document.getElementById(inputField).value); //first try to get the value the regular way
console.log(
get_type(
document.getElementById(inputField)
)
); //also try get_type to see if it exists, we're expecting a string
}
//stole this function from a stackoverflow post
function get_type(thing) {
if (thing === null) return "[object Null]"; // special case
return Object.prototype.toString.call(thing);
}
</script>
</html>
You're missing quotes:
document.getElementById(inputField);
Should be:
document.getElementById('inputField');
Based on #Schlaus answer, I created a jsfiddle with correct answer.
function printType() {
console.log(document.getElementById('inputField').value); //first try to get the value the regular way
console.log(
get_type(
document.getElementById('inputField')
)
); //also try get_type to see if it exists, we're expecting a string
}
Another code to debug for me have to keep it the same as can't rewrite. But Im wondering why newQuote is spitting the error undefined. I also believe that I need to fix the timer setting to get it display as the var tick isn't being called but not 100% sure there any advice is appreciated as I can't find any error beyond the newQuote undefined
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta charset="utf-8" />
<title>Random Proverbs</title>
<script type="text/javascript">
<!-- HIDE FROM INCOMPATIBLE BROWSERS
function changeQuote() {
quotes = new Array;
quotes[0] = "Laughter is the best medicine.";
quotes[1] = "Never look a gift horse in the mouth.";
quotes[2] = "One good turn deserves another.";
quotes[3] = "The early bird catches the worm.";
quotes[4] = "Two is company, three is a crowd.";
var newQuote = quotes[Math.round(Math.random()+quotes.length)];
document.quoteform.quote.value = newQuote;
}
var tick = setInterval(changeQuote(), 1000); //missing time in milliseconds and double quotes not needed
// STOP HIDING FROM INCOMPATIBLE BROWSERS -->
</script>
</head>
<body>
<form id="quoteform" action=""> <!--Was -->
<input type="text" size="50" id="quote" name="quote" /><br />
</form>
</body>
</html>
change document.quoteform.quote to document.forms.quoteform.quote
then name the form quoteform
so the new javascript would look like
function changeQuote() {
var quotes = new Array; //was var defintion
quotes[0] = "Laughter is the best medicine.";
quotes[1] = "Never look a gift horse in the mouth.";
quotes[2] = "One good turn deserves another.";
quotes[3] = "The early bird catches the worm.";
quotes[4] = "Two is company, three is a crowd.";
var newQuote = quotes[Math.floor(Math.random()*quotes.length)];
document.forms.quoteform.quote.value = newQuote;
}
setInterval(changeQuote, 1000);
then all you need is change the id to name in the opening form tag
You need to use Math.floor to avoid going outside the bounds of the array, and change the + to * to multiply the random number by the length of the array.
var newQuote = quotes[Math.floor(Math.random()*quotes.length)];
I've been trying to make a "Random Quote Machine" that randomly selects a quote from an array of 5 quotes and inserts the text into a paragraph on a webpage. The Machine uses HTML and JavaScript(jQuery). I suspect my error is pretty simple given how simple the project is.
Here's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
</body>
</html>
Here's the JavaScript:
var quotes = ["Innocence is thought charming because it offers delightful possibilities for exploitation.",
"Every day begins with an act of courage and hope: getting out of bed.",
"Hatred observes with more care than love does.",
"To understand someone, find out how he spends his money.",
"The educated do not share a common body of information, but a common state of mind."
];
function getQuote() {
return Math.floor(Math.random() * quotes.length);
}
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
Because your scripts are included in the head element, the quoteGen button doesn't exist in the DOM at the time that you try to bind an event handler to it. You need to either include the scripts just before the end of your body tag, or wrap your code in a DOM-ready event handler to ensure that the DOM exists as you expect it to when your code runs.
So, you could either go with this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</body>
</html>
... or, use a DOM-ready handler, such as this:
$(function () {
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
Works just fine?
http://jsfiddle.net/tj3dvz1m/.
make sure to run your code in a
$( document ).ready(function() {
Your code here.
});
The handler is being set before the #quoteGen dom node exists.
You need to move the inclusion of quotes.js to the end of your file, right before the closing of /BODY.
Or register the handler to be installed once the document is ready:
$(document).ready(function(){
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
This code works fine. Credit to owner.
// Random Quotes
var Quotation=new Array()
Quotation[0] = "Time is of the essence! Comb your hair.";
Quotation[1] = "Sanity is a golden apple with no shoelaces.";
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon.";
Quotation[3] = "Honesty blurts where deception sneezes.";
Quotation[4] = "Pastry satisfies where art is unavailable.";
Quotation[5] = "Delete not, lest you, too, be deleted.";
Quotation[6] = "O! Youth! What a pain in the backside.";
Quotation[7] = "Wishes are like goldfish with propellors.";
Quotation[8] = "Love the river's \"beauty\", but live on a hill.";
Quotation[9] = "Invention is the mother of too many useless toys.";
var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation()
{document.write(Quotation[whichQuotation]);}
showQuotation();
Good Day,
I am a newbie learning Javascript & Dojo and I typically learn by picking apart other parts of running code.
I am confused as to how to get a substring value from the following code (from the ArcGIS Sandbox):
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=7, IE=9, IE=10">
<!--The viewport meta tag is used to improve the presentation and behavior of the samples
on iOS devices-->
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<title>Query State Info without Map</title>
<script src="http://js.arcgis.com/3.6/"></script>
<script>
dojo.require("esri.tasks.query");
dojo.require("esri.map");
var queryTask, query;
require([
"esri/tasks/query", "esri/tasks/QueryTask",
"dojo/dom", "dojo/on", "dojo/domReady!"
], function(
Query, QueryTask,
dom, on
){
queryTask = new QueryTask("http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Demographics/ESRI_Census_USA/MapServer/5");
query = new Query();
query.returnGeometry = false;
query.outFields = ["SQMI","STATE_NAME","STATE_FIPS","SUB_REGION","STATE_ABBR","POP2000","POP2007","POP00_SQMI","POP07_SQMI","HOUSEHOLDS","MALES","FEMALES","WHITE","BLACK","AMERI_ES","ASIAN","OTHER","HISPANIC","AGE_UNDER5","AGE_5_17","AGE_18_21","AGE_22_29","AGE_30_39","AGE_40_49","AGE_50_64","AGE_65_UP"];
on(dom.byId("execute"), "click", execute);
function execute(stateName) {
query.text = dom.byId("stateName").value;
//execute query
queryTask.execute(query, showResults);
}
function showResults(results) {
var s = "";
for (var i=0, il=results.features.length; i<il; i++) {
var featureAttributes = results.features[i].attributes;
for (att in featureAttributes) {
s = s + "<b>" + att + ":</b> " + featureAttributes[att] + "<br>";
}
s = s + "<br>";
}
dom.byId("info").innerHTML = s;
}
});
</script>
</head>
<body>
US state name :
<input type="text" id="stateName" value="California">
<input id="execute" type="button" value="Get Details">
<br />
<br />
<div id="info" style="padding:5px; margin:5px; background-color:#eee;">
</div>
</body>
</html>
All I would like to do is pick apart the input (in this case the id="stateName" which is the word California).
So a silly example would be substituting the following code to get the first 10 characters of when someone types in 'California is on the west coast'
query.text = dom.byId("stateName").substring(0,10);
This is really so I can support other queries but I figured if I can do a substring on this input then it is really the same anytime when I query other attributes.
Thanks in advance for a newbie !
You need to get the innerHTML of your DOM element
query.text = dom.byId("stateName").value.substring(0, 10);
As Thomas Upton correctly pointed out the correct form would be:
dom.byId("stateName").value.substring(0, 10);
apparently the following also works
dom.byId("stateName").value.substr(0, 10);
As noted in comments, a call to .value will deliver what you need. Substring is a method on the string prototype See here. However, dom.byId returns a domNode. You don't want the substring of the domNode itself, you want the substring of the text value of the domNode. On inputs this is easily done with .value and is commonly done with .textContent and .innerHTML as well.