www.webdeveloper.com
Results 1 to 9 of 9

Thread: Passing array to a function. Possible in this case?

  1. #1
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,432

    Question 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>
    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; 
    }
    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; 
    }
    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?

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,498
    Would passing the object thisand the use of selectedIndex 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..?
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  3. #3
    Join Date
    Nov 2010
    Posts
    1,097
    I suspect 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; 
    }
    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...
    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?

  4. #4
    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_other.../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.

  5. #5
    ... and here it is without javascript:
    http://www.cutcodedown.com/for_other.../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.

  6. #6
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,432

    Thumbs up Thank you for the comments and code.

    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.

  7. #7
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,432

    Smile

    Quote Originally Posted by deathshadow View Post
    ... and here it is without javascript:
    http://www.cutcodedown.com/for_other.../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.
    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.
    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.
    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.
    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.

  8. #8
    Quote Originally Posted by JMRKER View Post
    Thank you again for your insite.
    With my posts, incite is more like it. Or at least, that's my inner spelling Nazi's insight on the topic.

    Quote Originally Posted by JMRKER View Post
    but under what conditions would the SELECT be more appropriately used?
    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.

    Quote Originally Posted by JMRKER View Post
    Is this a reference to the in-line style as opposed to an external CSS file?
    Correct. Having all that extra garbage in the scripting makes it harder to figure out what the scripting is doing.

    Quote Originally Posted by JMRKER View Post
    In the post #1 of this thread, I put everything (style, JS, external data) into the one file for ease of testing.
    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.

    Quote Originally Posted by JMRKER View Post
    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
    Then they probably don't know enough to answer your question. Good noise filter.

    Quote Originally Posted by JMRKER View Post
    nor that the path references might need to be changed for the script to work.
    Which is why you work pathless or down-tree.

    Quote Originally Posted by JMRKER View Post
    And are you referencing the BORDER of the table with your comment?
    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. ...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.

    Quote Originally Posted by JMRKER View Post
    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?
    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.
    Last edited by deathshadow; 06-26-2014 at 11:40 PM.

  9. #9
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,432
    Thanks for your comments and clarifications.
    I'll try to be more attentive.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles