/    Sign up×
Community /Pin to ProfileBookmark

Passing array to a function. Possible in this case?

The following code works fine, but I’m trying to make a modification that may not be possible.

[code]
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″ />
<title> Schedule Display </title>

<script type=”text/javascript”>
var ScedW2014 = [
[ ‘8:00′,”,’!Optics’,”,’!Optics’,’$Faculty’],
[ ‘8:30′,”,’!Lab’,”,’!Lab’,’$Committee’],
[ ‘9:00′,”,’!’,”,’!’,’$Meetings’],
[ ‘9:30′,”,’!’,”,’!’,’$’],
[’10:00′,”,’!Optics’,”,’!Optics’,”],
[’10:30′,”,’!Lab’,”,’!Lab’,”],
[’11:00′,”,’!’,”,’!’,”],
[’11:30′,”,’!’,”,’!’,”],
[’12:00′,’#COP’,”,”,”,”],
[’12:30′,’#’,”,”,”,”],
[ ‘1:00′,’#’,”,”,”,”],
[ ‘1:30′,’#’,”,”,”,”],
[ ‘2:00′,”,’#OTM-4’,”,”,”],
[ ‘2:30′,”,’#Lab’,”,”,”],
[ ‘3:00′,”,’#’,”,”,”],
[ ‘3:30′,”,’#’,”,”,”],
[ ‘4:00′,”,’#’,”,”,”],
[ ‘4:30′,”,’#’,”,”,”],
[ ‘5:00’,”,”,”,”,”]
];

var ScedF2014 = [
[ ‘8:00′,”,”,”,’#OTM-1′,’$Faculty’],
[ ‘8:30′,”,’!Optics’,’!Optics’,’#’,’$Committee’],
[ ‘9:00′,”,’!’,’!’,’#Lab B’,’$Meetings’],
[ ‘9:30′,”,’!Lab B’,’!Lab A’,’#’,’$’],
[’10:00′,”,’!’,’!’,”,”],
[’10:30′,”,’!Optics’,’!Optics’,”,”],
[’11:00′,”,’!’,’!’,”,”],
[’11:30′,”,’!Lab D’,’!Lab C’,”,”],
[’12:00′,’#OTM 1′,’!’,’!’,”,”],
[’12:30′,’#’,”,”,”,”],
[ ‘1:00′,’#’,”,”,”,”],
[ ‘1:30′,’#’,”,”,”,”],
[ ‘2:00′,’@OTM 3’,”,”,”,”],
[ ‘2:30′,’@’,”,”,”,”],
[ ‘3:00′,’@’,”,”,”,”],
[ ‘3:30′,’@’,”,”,”,”],
[ ‘4:00′,’@’,”,”,”,”],
[ ‘4:30′,’@’,”,”,”,”],
[ ‘5:00’,”,”,”,”,”]
];
</script>

</head>
<body>
<select onchange=”ShowSced(this.value)” class=”big”>
<option value=””>Choose Schedule</option>
<option value=”F2014″>Fall 2014</option>
<option value=”W2014″>Winter 2014</option>
</select>
<div id=”tableDIV”></div>

<script type=”text/javascript”>
function $_(IDS) { return document.getElementById(IDS); }

var bgc = [‘#66ff00′,’#cc99ff’,’#ffcccc’,’#cc9900′];
var dayLinks = [
‘http://www.nova.edu/~rumsey/rules.html’,
‘http://www.nova.edu/hpd/otm/gifs/crisis.html’,
‘http://www.nova.edu/hpd/otm/gifs/bhh.GIF’,
‘http://www.nova.edu/hpd/otm/gifs/complaint.html’,
‘http://www.nova.edu/hpd/otm/game/index.html’
];

var ScedCSVheading = [‘Time’,
‘<a href=”‘+dayLinks[0]+'”>Monday</a>’,
‘<a href=”‘+dayLinks[1]+'”>Tuesday</a>’,
‘<a href=”‘+dayLinks[2]+'”>Wednesday</a>’,
‘<a href=”‘+dayLinks[3]+'”>Thursday</a>’,
‘<a href=”‘+dayLinks[4]+'”>Friday</a>’
];

function ShowSced(info) {
var arr = [];
switch (info) {
case ‘W2014’: arr = ScedW2014.slice(0); break;
case ‘F2014’: arr = ScedF2014.slice(0); break;
default: break;
}
var str = ”; if (arr.length != 0) { str = ShowScedCSV(arr); }
$_(‘tableDIV’).innerHTML = str;
}

function ShowScedCSV(ScedCSV) {
var info = [];
info = ScedCSVheading.slice(0);
var str = ‘<table border=”1″>’;
str += ‘<thead><tr style=”background-color:#ffff00″>’;
for (j=0; j<info.length; j++) {
if (j == 0) { str += ‘<th style=”background-color:#ffff00″ width=”50px;”>’+info[j]+’&nbsp;</th>’; }
else { str += ‘<th style=”background-color:#ffff00″ width=”120px;”>’+info[j]+’&nbsp;</th>’; }
}
str += ‘</tr></thead>’;
str += ‘<tbody><tr>’;
for (i=0; i<ScedCSV.length; i++) {
info = ScedCSV[i].slice(0);
for (j=0; j<info.length; j++) {
if (j == 0) {
str += ‘<th style=”background-color:#ffff00″>’+info[j]+’&nbsp;</th>’;
} else {
tmp = info[j]; flg = -1;
if (tmp.charAt(0) == ‘!’) { flg = 0; }
if (tmp.charAt(0) == ‘@’) { flg = 1; }
if (tmp.charAt(0) == ‘#’) { flg = 2; }
if (tmp.charAt(0) == ‘$’) { flg = 3; }
if (flg == -1) {
str += ‘<th>’+tmp+’&nbsp;</th>’;
} else {
str += ‘<th style=”background-color:’+bgc[flg]+'”>’;
str += tmp.substr(1)+’&nbsp;</th>’;
}
}
} str += ‘</tr>’;
} str += ‘</tbody></table>’
return str;
}
</script>

</body>
</html>
[/code]

I use the <select> to determine which scheduling array to display.
onchange of this uses the value to send to the “ShowSced(info)” function.

The ‘info’ parameter is a string, but could it be an array reference instead?
I thought I could accomplish the same effect with

[code]
function ShowSced(arrInfo) { //
var str = ”;
if (arrInfo.length != 0) { str = ShowScedCSV(‘Sced’+arrInfo); } // should form ‘ScedF2014’ or ‘ScedW2014’, but No Good
$_(‘tableDIV’).innerHTML = str;
}
[/code]

or possibly…

[code]
<select onchange=”ShowSced(this.value)” class=”big”>
<option value=””>Choose Schedule</option>
<option value=ScedF2014>Fall 2014</option> <!– note use of array reference rather than string here –>
<option value=ScedW2014>Winter 2014</option>
</select>

function ShowSced(arrInfo) { //
var str = ”;
if (arrInfo.length != 0) { str = ShowScedCSV(arrInfo); }
$_(‘tableDIV’).innerHTML = str;
}
[/code]

but neither works.

Is there a way to pass the array to a function based upon the <select> user choice?
Is there a better way to accomplish the effect or is my original example the coding method of choice?

to post a comment
JavaScript

8 Comments(s)

Copy linkTweet thisAlerts:
@rootJun 26.2014 — Would passing the object [B][I]this[/I][/B]and the use of [B][I]selectedIndex[/I][/B] accomplish the task?

so then arrInfo.selectedIndex would return the index of the array that was selected.

Or am I not getting what you are trying to achieve..?
Copy linkTweet thisAlerts:
@xelawhoJun 26.2014 — I [B]suspect[/B] that the first one would work like this:
[CODE]
function ShowSced(arrInfo) { //
var str = '';
var arr=window['Sced'+arrInfo];
if (arrInfo.length != 0) { str = ShowScedCSV(arr); }

$_('tableDIV').innerHTML = str;
}
[/CODE]


being that your arrays are in page scope. Personally, I would put them into an object then you can address the keys as a string and get the arrays that way (provided that the select values match the object keys):
[CODE]
<script type="text/javascript">
var scheds={"W2014" : [
[ '8:00','','!Optics','','!Optics','$Faculty'],
[ '8:30','','!Lab','','!Lab','$Committee'],
[ '9:00','','!','','!','$Meetings'],
[ '9:30','','!','','!','$'],
['10:00','','!Optics','','!Optics',''],
['10:30','','!Lab','','!Lab',''],
['11:00','','!','','!',''],
['11:30','','!','','!',''],
['12:00','#COP','','','',''],
['12:30','#','','','',''],
[ '1:00','#','','','',''],
[ '1:30','#','','','',''],
[ '2:00','','#OTM-4','','',''],
[ '2:30','','#Lab','','',''],
[ '3:00','','#','','',''],
[ '3:30','','#','','',''],
[ '4:00','','#','','',''],
[ '4:30','','#','','',''],
[ '5:00','','','','','']
],
"F2014" : [
[ '8:00','','','','#OTM-1','$Faculty'],
[ '8:30','','!Optics','!Optics','#','$Committee'],
[ '9:00','','!','!','#Lab B','$Meetings'],
[ '9:30','','!Lab B','!Lab A','#','$'],
['10:00','','!','!','',''],
['10:30','','!Optics','!Optics','',''],
['11:00','','!','!','',''],
['11:30','','!Lab D','!Lab C','',''],
['12:00','#OTM 1','!','!','',''],
['12:30','#','','','',''],
[ '1:00','#','','','',''],
[ '1:30','#','','','',''],
[ '2:00','@OTM 3','','','',''],
[ '2:30','@','','','',''],
[ '3:00','@','','','',''],
[ '3:30','@','','','',''],
[ '4:00','@','','','',''],
[ '4:30','@','','','',''],
[ '5:00','','','','','']
]}
</script>

</head>
<body>
<select onchange="ShowSced(this.value)" class="big">
<option value="">Choose Schedule</option>
<option value="F2014">Fall 2014</option>
<option value="W2014">Winter 2014</option>
</select>
<div id="tableDIV"></div>

<script type="text/javascript">
function $_(IDS) { return document.getElementById(IDS); }

var bgc = ['#66ff00','#cc99ff','#ffcccc','#cc9900'];
var dayLinks = [
'http://www.nova.edu/~rumsey/rules.html',
'http://www.nova.edu/hpd/otm/gifs/crisis.html',
'http://www.nova.edu/hpd/otm/gifs/bhh.GIF',
'http://www.nova.edu/hpd/otm/gifs/complaint.html',
'http://www.nova.edu/hpd/otm/game/index.html'
];

var ScedCSVheading = ['Time',
'<a href="'+dayLinks[0]+'">Monday</a>',
'<a href="'+dayLinks[1]+'">Tuesday</a>',
'<a href="'+dayLinks[2]+'">Wednesday</a>',
'<a href="'+dayLinks[3]+'">Thursday</a>',
'<a href="'+dayLinks[4]+'">Friday</a>'
];

function ShowSced(info) {
var arr = scheds[info];
/* switch (info) {
case 'W2014': arr = ScedW2014.slice(0); break;
case 'F2014': arr = ScedF2014.slice(0); break;
default: break;
}
*/

var str = ''; if (arr.length != 0) { str = ShowScedCSV(arr); }
$_('tableDIV').innerHTML = str;
}

// etc...
[/CODE]


And it woulds seem to me that you could also move the object into the ShowSced function to get it out of global scope if you were that way inclined. Dunno if that answers your question?
Copy linkTweet thisAlerts:
@deathshadowJun 27.2014 — First off, this simply isn't something I'd be suggesting even doing client side if you care about people using it -- a lot of people block JavaScript intentionally or otherwise don't have it -- and some search engines won't see your content either. Just make proper pages of this stuff.

That said, if you insist on going down the "accessibility, what's that?" path of building this in JS, there are some issues that should be addressed and optimizations that could help.

1) get a NOSCRIPT tag in there warning people that you don't care about them.

2) don't use innerHTML, it's slow, forces a reflow, and is generally not how you're supposed to build scripted content in this day and age.

3) Since the select doesn't work scripting off either, it too should be built using the scripting.

4) an object of arrays (or object of objects of arrays) could make your categories easier to maintain.

5) do not set style from the scripting. That's not JS' job any more than it belongs in the markup. Likewise, don't use attributes like BORDER that have no business on any site written after 1997.

6) I'd consider putting it in an anonymous function just so you don't have to worry about any other scripts on whatever site this goes into conflicting with it... though making it a callable function able to handle multiple different data sets might make it more useful in the long run if you have many pages using the same type of info.

7) Ease up on 'slice' -- if you're going to use separate values, make them separate.

8) you might want to learn how to use SWITCH, if you are checking the same value over and over, it will be far, FAR more effective. (see your multiple IF for 'flg')

IF I were to use scripting to do this, it would probably be something like this:

http://www.cutcodedown.com/for_others/JMRKER/tableJS/template.html

The data in the markup (the part that changes/content), the external script being generic enough you can add/remove data and re-use it on other pages.

As with all my examples the directory:

http://www.cutcodedown.com/for_others/JMRKER/tableJS

Is unlocked for easy access to the bits and pieces.

BUT AGAIN, this simply is not something I'd ever do using JavaScript due to the fact you're displaying CONTENT... and generally content has no business being built using JS.

Gimme a few, and I'll toss together how I'd handle this without scripting.
Copy linkTweet thisAlerts:
@deathshadowJun 27.2014 — ... and here it is without javascript:

http://www.cutcodedown.com/for_others/JMRKER/tableCSS/template.html

as before, directory wide open for easy access to the goo.

http://www.cutcodedown.com/for_others/JMRKER/tableCSS/

You want to build the markup dynamically, do it on the server where it belongs. Uses the CSS3 'target' property, but if target is unavailable (IE8/earlier) all the tables are shown. Uses a hair more bandwidth, but has proper graceful degradation and would at least have a chance at search engines doing something with it.

... and it doesn't abuse a SELECT for something SELECT aren't meant to be used for.
Copy linkTweet thisAlerts:
@JMRKERauthorJun 27.2014 — Thank you '.' and 'xelawho' for your multiple suggestions.

All your suggestions worked with a minimal amount of changes.

Thank you as well 'deathshadow'. With the number of suggestions and the working code you provided,

I'm still wrapping my head around your comments to make sure I understand them.


All of your comments answered my initial question very well.

As for what I was trying to achieve, it is more of an exercise to learn than to create a world shattering site.

There are about 10+ years worth of Fall/Winter schedules I have that were hard coded into self-holding, hard-coded sites.

While the two samples used in the original post look sparse, there is actually more time accountability each semester.

I was getting tired of the copy/paste/modify cycle I went through at the start of each semester.


The information available is more for me and my students in the courses/labs that I teach.

Therefore the changes I was making were more along the quick-and-dirty trial/test of the one site (hence the use of the .innerHTML) rather than just write an index.html page to call the individual file sites. The actual data files are stored in one external .js file and are not part of the 'content' as shown in the original version of post #1.

Earlier versions of post #1 had multiple if...else statements and was becoming unwieldy.

I went to the switch...case version but thought that code was rather redundant

and that I should be able to compress it a bit. That prompted my initial question.


Anyway, thank you all for contributing to my learning experience. ?
Copy linkTweet thisAlerts:
@JMRKERauthorJun 27.2014 — ... and here it is without javascript:

http://www.cutcodedown.com/for_others/JMRKER/tableCSS/template.html

as before, directory wide open for easy access to the goo.

http://www.cutcodedown.com/for_others/JMRKER/tableCSS/

You want to build the markup dynamically, do it on the server where it belongs. Uses the CSS3 'target' property, but if target is unavailable (IE8/earlier) all the tables are shown. Uses a hair more bandwidth, but has proper graceful degradation and would at least have a chance at search engines doing something with it.

... and it doesn't abuse a SELECT for something SELECT aren't meant to be used for.[/QUOTE]


Thank you again for your insite.

I'm not sure I understand some of the things you reference in this and the earlier post.

If you have the time, could you expand your comments about the following:

... and it doesn't abuse a SELECT for something SELECT aren't meant to be used for.
[/quote]

I see how you use the <UL> to create the choices and it looks nicer,

but under what conditions would the SELECT be more appropriately used?



5) do not set style from the scripting. That's not JS' job any more than it belongs in the markup. Likewise, don't use attributes like BORDER that have no business on any site written after 1997.
[/quote]

Is this a reference to the in-line style as opposed to an external CSS file?


In the post #1 of this thread, I put everything (style, JS, external data) into the one file for ease of testing.

I most cases I try to use stand-alone code for the forum thread discussions because some beginners don't realize that the external files have a special format nor that the path references might need to be changed for the script to work.

And are you referencing the BORDER of the table with your comment?


7) Ease up on 'slice' -- if you're going to use separate values, make them separate.
[/quote]

I see how to now avoid using the slice so much, but is there an evil associated with copying or cloning an array using this method?

Thanks again for your demo code for me to learn from.
Copy linkTweet thisAlerts:
@deathshadowJun 27.2014 — Thank you again for your insite.[/quote]
With my posts, incite is more like it. ? Or at least, that's my inner spelling Nazi's insight on the topic.

but under what conditions would the SELECT be more appropriately used?[/quote]
SELECT is a FORM element, just like INPUT, BUTTON and TEXTAREA, which is why they have NO business outside a FORM... SELECT, BUTTON and TEXTAREA really having no business outside a fieldset either, with INPUT only belonging outside fieldsets for HIDDEN or SUBMIT. That's why they're FORM elements -- no matter how many people writing JavaScript abuse them to do anchor's job.

Is this a reference to the in-line style as opposed to an external CSS file?[/quote]
Correct. Having all that extra garbage in the scripting makes it harder to figure out what the scripting is doing.

In the post #1 of this thread, I put everything (style, JS, external data) into the one file for ease of testing.[/quote]
I've heard people say that, and I just don't get it. How having code that has nothing to do with the actual logic flow in the way is 'easier', or how editing it out in production code (a lame excuse that is rarely actually done) is 'easier', or how putting it in the same file so you have to scroll up and down to get to it instead of having separate editor windows is 'easier'... well, do I have to post a pic of Mandy Patinkin again?

Pretty much though, even in testing I advise against that -- it's sloppy at best, harder to deal with at worst. Generally speaking STYLE as a tag has no business even existing, and as an attribute REALLY should be deprecated for all but a handful of corner cases. From scripting? Use it with an eyedropper... around two-thirds the stuff people use element.style for should be done with a class swap.

I most cases I try to use stand-alone code for the forum thread discussions because some beginners don't realize that the external files have a special format[/quote]
Then they probably don't know enough to answer your question. Good noise filter.

nor that the path references might need to be changed for the script to work.[/quote]
Which is why you work pathless or down-tree.

And are you referencing the BORDER of the table with your comment?[/quote]
Yup. Just like with IMG, it has no business in any code written after 1997... just like 'language' on a SCRIPT tag, the TARGET attribute when you don't have framesets, the CENTER tag, and a whole host of other idiocy that never should have existed in the first place. [i]...and wouldn't have if M$ and Nyetscape hadn't gone to war with each-other! Well, that and if the W3C wasn't so blasted toothless and didn't let itself get shoved around by the first person in the door with a checkbook. [/i]

I see how to now avoid using the slice so much, but is there an evil associated with copying or cloning an array using this method?[/quote]
Memory use. Every time you clone/copy you increase the memory footprint, and given how browser garbage collection is a buggy joke (yes Mozilla, I'm looking at you!) and mobile space with it's significantly smaller amount of available memory is more and more important, you have to keep that in mind.
Copy linkTweet thisAlerts:
@JMRKERauthorJun 27.2014 — Thanks for your comments and clarifications.

I'll try to be more attentive.

?
×

Success!

Help @JMRKER spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.29,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...