JavaScript wouldn't display results of code - javascript

I tried creating a simple JavaScript file based on my adaption of source code from MDN.
My JavaScript code (loughshore_clubs.js) is as follows
<!--
var Club = “Ballinderry” ;
function ClubType(name){
if (name == “Ardboe”){
return name ;
} else{
return “I'm not from “+ name + “.”;
}
}
var clubs {myClub: ClubType(“Ardboe”), club2: ClubType(Club),
club3:
ClubType(“Moortown”)}
console.log(clubs.myClub); //Ardboe
console.log(clubs.club2); //Ballinderry
console.log(clubs.club3); //Moortown
/-->
And the HTML source (test.html) is
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8">
<title></title>
<meta name="generator" content="LibreOffice 4.2.4.2 (Linux)">
<meta name="created" content="20150514;0">
<meta name="changed" content="20150514;211357234273120">
<style type="text/css">
<!--
#page { margin: 2cm }
p { margin-bottom: 0.25cm; color: #000000; line-height:
120% }
a:link { so-language: en-US }
-->
</style>
</head>
<body>
<script src="scripts/loughshore_clubs.js" />
</body>
</html>
What's the matter? One thing I do realise is that I should avoid saving HTML files using LibreOffice and stick with Bluefish. (which I have on Mac o/s X Yosemite)

Remove the first and last lines of your script. HTML comment tags make no sense in a .js file.
Then replace each of your ” characters with a proper ".
You're also missing an = between clubs and { here: var clubs {myClub:...
After these changes you should have:
var Club = "Ballinderry";
function ClubType(name){
if (name == "Ardboe") {
return name;
} else {
return "I'm not from " + name + ".";
}
}
var clubs = {
myClub: ClubType("Ardboe"),
club2: ClubType(Club),
club3: ClubType("Moortown")
};
console.log(clubs.myClub); //Ardboe
console.log(clubs.club2); //Ballinderry
console.log(clubs.club3); //Moortown

This should work:
var Club = "Ballinderry" ;
function ClubType(name){
if (name == "Ardboe"){
return name ;
} else{
return "I\'m not from "+ name + ".";
}
}
var clubs = {
myClub: ClubType("Ardboe"),
club2: ClubType(Club),
club3: ClubType("Moortown")
};
console.log(clubs.myClub); //Ardboe
console.log(clubs.club2); //Ballinderry
console.log(clubs.club3); //Moortown
You're right, you should stop saving code with LibreOffice, because it changed all your " to “. I recommend using atom
And you didn't have an = when declaring the clubs variable.
Once again, get atom, and then download the linter package and use JShint. That should get you in the habit of writing nice code. I use it myself. Tweet to me if you need more help, I started out two months ago and I just completed the backend for my first Node.js app.
Edit: The other answer beat me to it, he should get the vote. :P

Related

Adding html table to javascript using document.write

Looking for some help here. Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for:
Add code to the writeIt function that writes the opening table tag before iterating thru the heros and villians and then the closing table tag. Then modify the makeListItem to return a string in the form of tr td Hero td td Villan /td /tr.
I tried this but am getting a blank html page when try to view.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {"Super Man":["Lex Luther"],
"Bat Man":["Joker", "Riddler",],
"Spider Man":["Green Goblin",
"Vulture", "Carnage"],
"Thor":["Loki", "Frost Giants"]};
function writeIt('<table>'){
for (hero in superData){
var villains = superData[hero];
for (villainIdx in villains){
var villain = villains[villainIdx];
var listItem = makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
document.write(listItem);
}
}
}
function makeListItem(name, value){
var itemStr = "<li>" + name + ": " + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
Try this:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Functions</title>
<meta charset="utf-8" />
<script>
var superData = {
"Super Man": ["Lex Luther"],
"Bat Man": ["Joker", "Riddler", ],
"Spider Man": ["Green Goblin",
"Vulture", "Carnage"
],
"Thor": ["Loki", "Frost Giants"]
};
function writeIt() {
document.write('<table>');
for (hero in superData) {
document.write("<tr><td>" + hero + ": <ul>");
var villains = superData[hero];
for (villainIdx in villains) {
var villain = villains[villainIdx];
var listItem = makeListItem(villain);
document.write(listItem);
}
document.write("</ul></td></tr>");
}
}
function makeListItem(value) {
var itemStr = "<li>" + value + "</li>";
return itemStr;
}
document.write('</table>');
</script>
</head>
<body onload="writeIt()">
</body>
</html>
I tried this but am getting a blank html page when try to view.
Because you have syntax problems. Use F12 or the Inspector/Developer mode to find out why.
Our class instructor is asking us to add a table into javascript using the document.write, I know this is not the recommended way to do this, but this is what our instructor is looking for
True, it's often frowned upon, but JavaScript makes it available for a reason, so let's use it.
The first problem is that you seem to have transposed some code...
For example, you have function writeIt('<table>'). I think you meant document.write('<table>');.
function writeIt(){
document.write('<table>');
Next, you have your final document.write outside of your function call.
document.write('</table>');
This should be inside writeIt(), just after your for loop.
Finally, you have some unquoted stuff in your loop...
makeListItem(<tr><td>Hero</td><td>Villan</td></tr>);
Should be (single or double quotes):
makeListItem('<tr><td>Hero</td><td>Villan</td></tr>');
But that's still a bit off for a table. For example, Superman has a 1:1 ratio with his villains and Batman has a 1:2 ratio. You should be adding your rows and tables in a more predictable manner, but the above will at least start to give you output to work from.
Finally, an observation is that your makeListItem needs to use <ul> before it uses <li> so those problems need to be resolved. For now, I recommend you just spit the data out and format it later.

How to get substring using Dojo and javascript

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.

grid 960 - while executing inspectSection in dmx960 grid, js error occurred.

I'm trying to run this grid extention in DW CS5. I'm a front end person so debugging other people's code isn't my thing. So when I try set the grid precepts I get this error:
while executing inspectSection in dmx960 grid, js error occurred.
Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Barefoot Development Group</title>
<link href="CSS/Style.css" rel="stylesheet" type="text/css">
<link href="CSS/text.css" rel="stylesheet" type="text/css">
<link href="CSS/reset.css" rel="stylesheet" type="text/css">
</head>
<body>
<!------start container------->
<div id = "container" class ="container_16"></div>
<div id = "social_search" class = "grid_16"></div>
<div id = "social_links" class = "grid_1 alpha"></div>
<!------Main container-------->
<!------Header start---------->
<!------Social Links---------->
<!-------End social links------>
<!----start Social icons -------->
<!----end social icons----->
</body>
</html>
I tried deleting the cache in Config folder and reinstalling the extension. Didn't work. I checked the log files and found this:
JS Error: theElem.getAttribute is not a function filename:
C:\Users\cvr\AppData\Roaming\Adobe\Dreamweaver
CS5\en_US\Configuration\Shared\DMXzone\960 Grid\dmx960grid_lib.js
lineno: 598
So I went to the JS file and here is what I found in this expression block:
function getGridClassNum(theElem) {
if (!theElem) return 0;
var cls = theElem.getAttribute("class");
if (!cls) return 0;
if (cls == 'clearfix') {
//Try to read the parent
var parent = getGridElement(theElem.parentNode);
if (parent && parent.nodeType === Node.ELEMENT_NODE) {
return getGridClassNum(parent);
}
} else {
var numMatch = cls.match(new RegExp("\\b(grid|container)_(\\d+)\\b"));
if (numMatch && numMatch.length > 1) {
return parseFloat(numMatch[2]);
// //decrease with prefix and suffix
// - getGridClassNameNum(theElem, 'prefix')
// - getGridClassNameNum(theElem, 'suffix');
}
}
return 0;
}
I don't see anything particularly amiss here. But perhaps a more expert debugger can tell me if there is something going on here. Here is what confuses me - I was looking for the function inspectSection but I couldn't find it. I'm left scratching my head here.
Could this be a problem of including the script directly into the html doc?
Thanks!

Getting a checkbox to write a JavaScript cookie

I've got a page with a splash screen, where users select one of two languages in which the rest of the site will be displayed. Next to each language option is a "remember my choice", HTML form, checkbox. How can I have the selected checkbox write a cookie with the language preference, which would skip the splash screen on future visits?
May be you can use something like below, Note code not tested:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function setCookie(c_name,value,expiredays) {
var exdate=new Date()
exdate.setDate(exdate.getDate()+expiredays)
document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate)
}
function getCookie(c_name) {
if (document.cookie.length>0) {
c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1) {
c_start=c_start + c_name.length+1
c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return null
}
onload=function(){
document.getElementById('linksNewWindow').checked = getCookie('linksNewWindow')==1? true : false;
}
function set_check(){
setCookie('linksNewWindow', document.getElementById('linksNewWindow').checked? 1 : 0, 100);
}
</script>
</head>
<body>
<div>Hi</div>
<input type="checkbox" id="linksNewWindow" onchange="set_check();">
</body>
</html>
This is a great reference for javascript cookies, http://www.quirksmode.org/js/cookies.html, I suggest doing this with PHP other than javascript simply because I the cookies and session functions are much more powerful with server-side scripting.
document.cookie
^ this is the js code that represents a pages cookies.

Returning currently displayed index of an array Javascript

I have a simple array with x number of items. I am displaying them individually via a link click... I want to update a number that say 1 of 10. when the next one is displayed i want it to display 2 of 10 etc...
I have looked all around and my brain is fried right now... I know its simple I just cant get it out.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Page Title</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" charset="utf-8"/>
<script type="text/javascript">
var quotations = new Array()
quotations[0]= "abcd"
quotations[1]= "efgh"
quotations[2]= "ijkl"
quotations[3]= "mnop"
quotations[4]= "qrst"
quotations[5]= "uvwx"
quotations[6]= "yzab"
numQuotes = quotations.length;
curQuote = 1;
function move( xflip ) {
curQuote = curQuote + xflip;
if (curQuote > numQuotes)
{ curQuote = 1 ; }
if (curQuote == 0)
{ curQuote = numQuotes ; }
document.getElementById('quotation').innerHTML=quotations[curQuote - 1];
}
var curPage = curQuote
</script>
</head>
<body>
<div id="quotation">
<script type="text/javascript">document.write(quotations[0]);</script>
</div>
<div>
<p>GO back
<script type="text/javascript">document.write(curPage + " of " + numQuotes)</script>
GO FORTH</p>
</div>
</body>
</html>
Edit: curQuote is not updating dynamically... it stays at '1' when next is clicked.
In your code, curQuote is already the value you want. I rewrote everything to clean it up and show some better logic/syntax. Note that ideally you would be attaching the click handlers via DOM methods and not using inline handlers, but for simplicity I've left it that way here.
Working version viewable here: http://jsbin.com/irihu3/2
<html>
<head>
<title>Quotations</title>
<script type="text/javascript" charset="utf-8">
var quotations = ["hi", "how", "are", "you", "today", "good", "sir"],
lastIndex = quotations.length - 1,
currentIndex = 0;
function move(xflip) {
currentIndex = currentIndex + xflip;
if (currentIndex > lastIndex) {
currentIndex = 0;
} else if (currentIndex < 0) {
currentIndex = lastIndex;
}
document.getElementById('quotation').innerHTML = quotations[currentIndex] + " (Quote #" + (currentIndex + 1) + ")";
return false;
}
</script>
</head>
<body>
<div id="quotation">hi (Quote #1)</div>
<a onclick="move(-1);">Prev</a>
<a onclick="move(1)">Next</a>
</body>
</html>
Some things to note:
Always declare variables with the var keyword or you create global variables.
You can combine multiple variable declarations into one statement by separating them with commas. It's good practice to stick to one var statement and to put it at the top of your code/function.
All you really need to keep track of here is the current index of the array, not the quote itself. It's also not important how long the array is, just what the last index is. As such, in my code I am using currentIndex and lastIndex instead of curQuote and numQuotes.
Using return false; at the end of your function will suppress the default action when clicking on a hyperlink (not following the link). This is what you want in this case, because you're using a hyperlink to trigger behavior on the page and not actually navigating to another page.
You're making a lot of beginner mistakes in your JavaScript but it seems as if curQuote has the value you want, no?
Tips:
You can declare an array as such: var array = [1,2,3,4,5,6,7];
Terminate statements with a semi-colon.
Use var keyword for local variables.
Don't put braces around one line if statements bodies.
Use indentation properly to make the code readable.
Try this
var curPage = quotations[curQuote];

Categories

Resources