JavaScript - Two Dimensional Array / Sorting And Combining / Coding Problem
Hi everyone
I'm having a hard time, wrapping my head around an array sort+combine function. I have an array which would look somewhat (these are simplified numbers) like this Code: TestArray = [ ["222222","1"], ["222222","1"], ["222222","1"], ["333333","1"] ["111111","1"], ["000000","2"], ["111111","2"], ["111111","2"], ["222222","20"], ]; I got it as far as to be sorted like this: Code: SortedArray = [ ["000000","2"], ["111111","1"], ["111111","2"], ["111111","2"], ["222222","1"], ["222222","1"], ["222222","20"], ["222222","1"], ["333333","1"] ]; And from there to this: Code: BadlyMergedArray = [ ["000000","2"], ["111111,"1","2"], ["222222","1","20","1"], ["333333","1"] ]; But I want to end up with this: Code: MergedArray = [ ["000000","2"], ["111111","1","2"], ["222222","1","20"], ["333333","1"] ]; So the first part of the inner arrays is the first item to be sorted and combined by. After that, the smaller numbers have to do practically the same, while staying in the correct order under the first sort. I'm only a spare time programmer, and my code is probably one of the most confusing pieces of code ever written. I am assuming that this is some fairly easy stuff for one of you guys. I can post my code, but I think there's a much easier solution to it, so I wanted to see if someone can point me in the right direction, or show me how this is properly done. Thanks so much! here's to hoping! patrick/shootingpandas Similar TutorialsHello, I need your help. I'd like to structure and build an array like the below.: Code: var provinces = [ ['Ontario','ON'], ['Quebec','QC'], ['British Columbia','BC'], ['Saskatchewan','SK'] ]; then, id like to compare the value (x) against my array ie. Code: var x = 'Ontario' if (x matches the first value in the array 'provinces') { then let x = ON } How do you write something like this in javascript? Much thanks and appreciation for all your help, Cheers, Jay Short version: I'm having trouble with "moving subarrays" in a multidimensional associative array. Long version: (Yes, I know that there's technically no such thing as a js associative array and that I'm actually using a generic object.) This is one of those annoying questions for which significant code can't be shown. I'm fetching a JSON object from PHP and parsing it as multi-dimensional associative array that comes out with this "structure": Code: obj[regions][variables][years] = value; My presentation logic works fine for that. Year data is presented for each variable, and variables are grouped by region. For reference, if needed, the display is tabular and similar to this: Code: Regions | Variables | 2003 | 2004 | 2005 ========================================= | measure1 | abcd | efgh | ijkl ================================= county1 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= | measure1 | abcd | efgh | ijkl ================================= county2 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= | measure1 | abcd | efgh | ijkl ================================= county3 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= | measure1 | abcd | efgh | ijkl ================================= county4 | measure2 | mnop | qrst | uvwx ================================= | measure3 | yzab | cdef | ghij ========================================= My problem comes from trying to allow the option to reorganize the grouping - that is, turning it into regions grouped by variable. The display logic can handle it, but I can't get the array handling code right. The desired secondary structure is Code: obj[variable][region][year] = value; Some things I've tried: Code: /* obj is in the format of obj[region][variable][year] = value */ data_arr = new Array(); for (var region in obj) { for (var variable in obj[region]) { for (var year in obj[region][variable]) { /* fail one */ data_arr[variable][region][year] = obj[region][variable][year]; /* data_arr[variable] is undefined */ /* fail two */ y = obj[region][variable][year]; y_arr = new Array(); y_arr[year] = y; r_arr = new Array(); r_arr[region] = y_arr; data_arr[variable] = r_arr; /* only the values from the last iteration are displayed */ /* fail three */ y = obj[region][variable][year]; y_arr = new Array(); y_arr[year].push(y); r_arr = new Array(); r_arr[region].push(y_arr); data_arr[variable].push(r_arr); /* y_arr[year] is undefined */ } } } And then other permutations of those three. I could run through it easy if not needing the textual index, but that's actually part of my display data, so it has to stay. Can anyone help me with what I'm overlooking? Hello, First of all, I am not a coder. I can put together some fairly simple HTML, and can borrow chunks of JS code to suit certain basic purposes. Also, I am terribly sorry if my technical lingo is way off target. I have managed to accomplish two separate goals using javascript, but am having trouble combining their results. I have created an image link that randomly calls a URL from an array. I also have a separate roll-over image. What I am trying to do is have the link that accesses the array also be a roll-over image. I can't seem to accomplish this. http://matrix.senecac.on.ca/~mlinhar...low/page7.html This URL is what I am working on. The "b" symbol is the roll-over. The "right" arrow accesses an array at: http://matrix.senecac.on.ca/~mlinhar...w/randomize.js I have tried simply adding my roll-over code to randomize.js and adjusting the array accordingly, but that doesn't seem to work. I would like the "right" arrow to be a roll-over image as the "b" symbol is, but also access the "randomize" array as it currently does. My problem is that my understanding of JS isn't great enough to determine how separate pieces of code might be combined or function together. Anyways, I'm sorry if my technical knowledge and abilities are too underdeveloped for this forum. I would appreciate any and all advice anyone might have. I am trying to make an addition to a .js plugin for a wiki. Currently it does not support sorting my IP address. So far I have created the below code which does more than the script initially did, but is still not sorting 100% correctly. Any tips? Code: sort_ipaddr: function(a,b){ aa = a[0].split(".",4); bb = b[0].split(".",4); var counti = 0; for (var i=0; i<4; i++) { if (parseInt(parseFloat(aa[i])) == parseInt(parseFloat(bb[i]))){} if (parseInt(parseFloat(aa[i])) < parseInt(parseFloat(bb[i]))){counti--} if (parseInt(parseFloat(aa[i])) > parseInt(parseFloat(bb[i]))){counti++} } return counti; }, EDIT I've also tried this which is closer but still not there. Code: sort_ipaddr: function(a,b){ aa = a[0].split(".",4); bb = b[0].split(".",4); var resulta = (aa[3]+(aa[2]*256)+(aa[1]*256*256)+(aa[0]*256*256*256)); var resultb = (bb[3]+(bb[2]*256)+(bb[1]*256*256)+(bb[0]*256*256*256)); return resulta-resultb; }, This results in a list like so: 10.1.15.22 10.1.16.22 10.1.15.23 10.1.15.24 10.1.16.24 10.1.15.25 So, I'm using code like the following and getting errors: result = a list of cars with each property separated by ',' and each car separated by '|' This code creates and populates the array (seems to work) Code: var carList = new Array(); var cars = new Array(); var properties = new Array(); cars = result.split("|"); for(var i=0; i<cars.length;i++){ properties = cars[i].split(","); carlist[carlist.length++] = new car(items[0],items[1],items[2]); function car(id,make,model){ carID = id; carMake = make; carModel = model; } Later, I want to sort the array and call it like this: carList.sort(carSort); here's the sort code Code: function carSort(a, b){ var x = a.carMake.toLowerCase(); var y = b.carMake.toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } I get the error that "a.carMake does not exist" (in firebug). What am I doing wrong? I am trying to sort an array of strings based on the location of a string called "this.oText.value" inside an array of strings called "aList." If "this.oText.value" comes earlier in an entry in aList (call it "a") than another entry "b", I want "a" to appear before "b". Clearly, there is something very wrong with my code. It really isn't doing anything as of right now. Code: aList.sort(sortArray); function sortArray(a,b) { if(a.toLowerCase().indexOf(this.oText.value.toLowerCase()) < b.toLowerCase().indexOf(this.oText.value.toLowerCase())) return 1; else if(a.toLowerCase().indexOf(this.oText.value.toLowerCase()) > b.toLowerCase().indexOf(this.oText.value.toLowerCase())) return -1; else return 0; } What I need help with is sorting the [0] of my array. I need it to sort so that if the user puts in his last name, whether its uppercase or lowercase (Adams, adams), it will sort through the list of students I add, and put them in an alphabetic order i.e adams, Adams, cook, Douglas....and so on. Here is the code that I have below for just sorting by last name, which will seperate the lowercase entries from the uppercase entries. That would be the opposite of what I want. I had it sorted so that it would sort the [o], which is where the last name value is located. Any thoughtful help would be appreciated. Code: function Last_names( s1, s2 ) { if ( s1[0] > s2[0] ) return 1; return 0; } function sortLast(form) { StudentsLists.sort( Last_names ); windows(form);//calling the windows function each time the sortLast function is called } Code: var myarray2=[25, 8, 7, 41]; myarray2.sort(function(a,b){return a - b}) I have tried this code and it works. What I don't understand is, how does array understand which value should be taken as "a" and "b" ? How does javascript understand what is to be done with values, if it is not specified by coding logic ? Is there some kind of in-built functionality ? How is that functionality triggered ? Do I not require further coding as Code: for(i=0; i<myarray2.length; i++){ j=i+1; for((myarray2[i]-myarray2[j])>0){ var a = myarray2[i]; myarray2[i] = myarray2[i+1]; myarray2[i+1] = a; j=j+1;} } and then run two loops for two comparing two values ? Thanks Hi All. I have a dynamic Coldfusion form which adds multiple addresses which holds fields like Town, Postcode, ResidentFromDate, ResidentToDate... and on click of the save button I have a script function that runs which I am trying add all the elements of this form into an array and then sort by ResidentFromDate and output the results... Here is what I have at the minute but my sort does not seem to be working and is throwing out results in the following order (10/2006, 01/2005, 08/2006, 01/2007) and that is clearing not in descending order... If someone could take a look at my script and tell me what is wrong I would be much appreciated (see below) * I seem to be getting results and it is just not sorting correctly, so my theory is something is up with the part where I am calling addresses.sort. Code: var dates = { convert:function(d) { // Converts the date in d to a date-object. The input can be: // a date object: returned without modification // an array : Interpreted as [year,month,day]. NOTE: month is 0-11. // a number : Interpreted as number of milliseconds // since 1 Jan 1970 (a timestamp) // a string : Any format supported by the javascript engine, like // "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc. // an object : Interpreted as an object with year, month and date // attributes. **NOTE** month is 0-11. return ( d.constructor === Date ? d : d.constructor === Array ? new Date(d[0],d[1],d[2]) : d.constructor === Number ? new Date(d) : d.constructor === String ? new Date(d) : typeof d === "object" ? new Date(d.year,d.month,d.date) : NaN ); }, compa function(a,b) { // Compare two dates (could be of any type supported by the convert // function above) and returns: // -1 : if a < b // 0 : if a = b // 1 : if a > b // NaN : if a or b is an illegal date // NOTE: The code inside isFinite does an assignment (=). return ( isFinite(a=this.convert(a).valueOf()) && isFinite(b=this.convert(b).valueOf()) ? (a>b)-(a<b) : NaN ); }, inRange:function(d,start,end) { // Checks if date in d is between dates in start and end. // Returns a boolean or NaN: // true : if d is between start and end (inclusive) // false : if d is before start or after end // NaN : if one or more of the dates is illegal. // NOTE: The code inside isFinite does an assignment (=). return ( isFinite(d=this.convert(d).valueOf()) && isFinite(start=this.convert(start).valueOf()) && isFinite(end=this.convert(end).valueOf()) ? start <= d && d <= end : NaN ); } } // define array var addresses = []; // if atAddrSince is greater than 5 years from today if (atAddrSince > addrFromValidate) { // loop round each previous address for (i=1;i<=maxID;i++) { var addrPart = []; if (eval('document.fmAddPrevAddr.address1'+i)) { var address1 = eval('document.fmAddPrevAddr.address1'+i+'.value'); var town = eval('document.fmAddPrevAddr.town'+i+'.value'); var country = eval('document.fmAddPrevAddr.country'+i+'.value'); var postcode = eval('document.fmAddPrevAddr.postcode'+i+'.value'); var residentfrom = eval('document.fmAddPrevAddr.ataddrsince'+i+'.value'); var residentto = eval('document.fmAddPrevAddr.ataddrto'+i+'.value'); // insert into array addrPart[0]=address1; addrPart[1]=town; addrPart[2]=country; addrPart[3]=postcode; addrPart[4]=residentfromdate; addrPart[5]=residenttodate; addresses.push(addrPart); } } addresses.sort(sortfunction) function sortfunction(a, b) { if(dates.compare(a[4],b[4]) == -1) { return true; } else { return false; } } for (var v=0;v<addresses.length;v++) { var addresses1 = addresses[v]; alert(addresses1[4]); } } Many Thanks, George I have a code that I implemented on my site. I was wondering if there was a way to had an active link within the 'blurb' section? I'm not familiar with Javascript... var blurb = new Array(); blurb[0]="Text 1" blurb[1]="Text 2" blurb[2]="Text 3" blurb[3]="Text 4" blurb[4]="Text 5<br>More text<br>Add a link" blurb[5]="www.link.com" for (i=0; i < aryImages.length; i++) { var preload = new Image(); preload.src = aryImages[i]; } function swap(imgIndex) { document['imgMain'].src = aryImages[imgIndex]; TheText = blurb[imgIndex]; document.getElementById('blurbarea').innerHTML=TheText; } Any help would be great!! Hi All, I am using JqGrid (http://www.trirand.com/blog/jqgrid/jqgrid.html) to display data in my application. In jqGrid I found a problem with IPAddress. If anyone of the column in JqGrid have IPAddress value, then sorting functionality in the jqGrid is not working properly. Can you please let me know any solution for this problem? Advance Thanks... I am trying to use JavaScript in conjuntion with html to display a table of sortable cities, states and dates. The dates are my problem. I am a novice and was given this code. But it seems to sort in European style, yyyy/mm/dd. I need it to sort mm/dd/yyy, which i am told is US style. Any help on this, I would be most grateful for. I have placed a page here to let you see the code at work. This page has the code on it in text also. I do not mind posting the code hgere also if you prefer. Thanks for any help you may be willing to offer me with this. Preston Hi, I have written this program: Code: var scores=[]; function sortScores(scoreRecs){ for(i=0;i<scoreRecs.length;i++) scores.push(scoreRecs[i]); for(var i=0;i<scores.length;i++) { for(var j=i+1;j<scores.length;j++) { if(Number(scores[i])>Number(scores[j])) { tempValue=scores[j]; scores[j]=scores[i]; scores[i]=tempValue; } } } alert(scores); } sortScores(["5","6","5","7","7"]); to take an array of variables in calling the function (ie sortScores), place these variables into an empty array("scores"), apply the bubble sort to scores, and then alert scores in sorted form. When I use test values like I have above, where they are all just numbers, this program works perfectly and alerts the "scores" array, correctly sorted. However, what I would like to do is to call the function with an array of records, each containing two fields, and apply the same sort to the array of records, based on the value in the first field of each record.To illustrate, i'd like to be able to call the function thus: Code: sortScores([{sco 0,index:0},{sco 2, index:1},{sco 1,index:2}]); and for it to sort the records in descending order of the value of the "score" field. So the above call would alert: Code: [{sco 2,index:1},{sco 1,index:2},{sco 0,index:0}] however, i'm not sure how i'd reference the numeric part of the f1 of each record in the sort? Hopefully you can see what I'm trying to achieve...any ideas would be greatly appreciated. Hello everybody, I have a nice search engine but its seems i can't put it twice on the same page: Code: <script language="JavaScript"> function startSearch(){ searchString = document.searchForm.searchText.value; if(searchString != ""){ searchEngine = document.searchForm.whichEngine.selectedIndex + 1; finalSearchString = ""; if(searchEngine == 1){ finalSearchString = "http://www.altavista.digital.com/cgi-bin/query?pg=q&what=web&fmt=.&q=" + searchString; } if(searchEngine == 2){ finalSearchString = "http://av.yahoo.com/bin/query?p=" + searchString + "&hc=0&hs=0"; } if(searchEngine == 3){ finalSearchString = "http://www.excite.com/search.gw?trace=a&search=" + searchString; } if(searchEngine == 4){ finalSearchString = "http://www.hotbot.com/?SW=web&SM=MC&MT=" + searchString + "&DC=10&DE=2&RG=NA&_v=2&act.search.x=89&act.search.y=7"; } if(searchEngine == 5){ finalSearchString = "http://www.infoseek.com/Titles?qt=" + searchString + "&col=WW&sv=IS&lk=noframes&nh=10"; } if(searchEngine == 6){ finalSearchString = "http://www.lycos.com/cgi-bin/pursuit?adv=%26adv%3B&cat=lycos&matchmode=and&query=" + searchString + "&x=45&y=11"; } if(searchEngine == 7){ finalSearchString = "http://netfind.aol.com/search.gw?search=" + searchString + "&c=web&lk=excite_netfind_us&src=1"; } location.href = finalSearchString; } } // --> </script> <basefont face="Verdana, Arial, sans-serif"> <form name="searchForm"> <table width=320 border cellpadding=3 cellspacing=2 bgcolor=444444> <tr> <td bgcolor=lightblue><font size=1 face="Verdana, Arial, sans-serif">Search for:<br> <td bgcolor=lightblue><font size=1 face="Verdana, Arial, sans-serif">Search from: <td bgcolor=lightblue> <tr> <td bgcolor=navajowhite><input style="background: dddddd" name="searchText" type="text"> <td bgcolor=navajowhite> <select style="background: dddddd" name="whichEngine"> <option selected>Altavista <option>Yahoo! <option>Excite <option>Hotbot <option>Infoseek <option>Lycos <option>AOL Netfind </select> <td bgcolor=navajowhite><input type="button" value="Send" onClick="startSearch()"> </select> </table> </form> Can someone tell me how to put the code twice in the html page without creating a conflict as a result of identical codes? Ok, with a little help I was able to write up this script, but whenever I put it onto my page it will not show up. Any idea on what I need to add? Code: <head> <!-- stylesheets --> <link rel="stylesheet" href="http://web-kreation.com/demos/Sliding_login_panel_jquery/css/style.css" type="text/css" media="screen" /> <link rel="stylesheet" href="http://web-kreation.com/demos/Sliding_login_panel_jquery/css/slide.css" type="text/css" media="screen" /> <!-- PNG FIX for IE6 --> <!-- http://24ways.org/2007/supersleight-transparent-png-in-ie6 --> <!--[if lte IE 6]> <script type="text/javascript" src="http://alig.mezoka.com/slider/js/pngfix/supersleight-min.js"></script> <![endif]--> <!-- jQuery - the core --> <script src="http://alig.mezoka.com/slider/js/jquery-1.3.2.min.js" type="text/javascript"></script> <!-- Sliding effect --> <script src="http://alig.mezoka.com/slider/js/slide.js" type="text/javascript"></script> </head> </body> <!-- BEGIN switch_user_login_form_header --> <!-- Panel --> <div id="toppanel"> <div id="panel"> <div class="content clearfix"> <div class="left"> <!-- Login Form --> <form class="clearfix" action="http://www.roleplayandwritinghaven.com/login.forum?connexion" method="post"> <h1>Member Login</h1> <label class="grey" for="log">Username:</label> <input class="field" type="text" name="username" id="log" value="" size="23" /> <label class="grey" for="pwd">Password:</label> <input class="field" type="password" name="password" id="pwd" size="23" /> <label>Log me on automatically at each visit: <input name="autologin" checked="checked" type="checkbox"></label> <div class="clear"></div> <input type="submit" name="submit" value="Login" class="bt_login" /> <a class="lost-pwd" href="#">Lost your password?</a> </form> </div> <div class="left right"> <!-- Register Form --> <form action="http://www.roleplayandwritinghaven.com/profile.forum?mode=register" method="post"> <h1>Not a member yet? Sign Up!</h1> <label class="grey" for="signup">Username:</label> <input class="field" type="text" name="signup" id="signup" value="" size="23" /> <label class="grey" for="email">Email:</label> <input class="field" type="text" name="email" id="email" size="23" /> <label>A password will be e-mailed to you.</label> <input type="submit" name="submit" value="Register" class="bt_register" /> </form> </div> </div> </div> <!-- /login --> <!-- The tab on top --> <div class="tab"> <ul class="login"> <li class="left"> </li> <li>Hello Guest!</li> <li class="sep">|</li> <li id="toggle"> <a id="open" class="open" href="#">Log In | Register</a> <a id="close" style="display: none;" class="close" href="#">Close Panel</a> </li> <li class="right"> </li> </ul> </div> <!-- / top --> </div> <!--panel --> <!-- END switch_user_login_form_header --> </body> I am new to JavaScript and am enrolled in an introductory class. My assignment is to create JavaScript for a Web page that counts down the time left until several events. I have been working on this code for several hours now, and I have done everything the textbook instructs me to do, yet when I load the Web page I still get blank fields where my countdown info should be. I would really appreciate it if someone could look through the code I've created and give me some pointers. I have an .htm file and an external .js file. The .htm file is: Code: <html> <head> <!-- New Perspectives on JavaScript Tutorial 2 Review Assignment Events in Dixon Author: Date: Filename: events.htm Supporting files: dates.js, dixon.css, logo.jpg --> <title>Upcoming Events at Dixon</title> <link href="dixon.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="dates.js"></script> <script type="text/javascript"> function showCountdown() { var today = new Date("December 1, 2007 6:31:45"); var Date1 = new Date("January 14, 2007 10:00:00"); var Date2 = new Date("May 21, 2007 12:00:00"); var Date3 = new Date("July 4, 2007 21:00:00"); var Date4 = new Date("September 1, 2007 12:00:00"); var Date5 = new Date("December 1, 2007 11:30:00"); var Date6 = new Date("December 31, 2007 15:30:00"); document.eventform.thisDay.value = showDateTime(today); changeYear(today, Date1); changeYear(today, Date2); changeYear(today, Date3); changeYear(today, Date4); changeYear(today, Date5); changeYear(today, Date6); document.eventform.count1.value = countdown(today, Date1); document.eventform.count2.value = countdown(today, Date2); document.eventform.count3.value = countdown(today, Date3); document.eventform.count4.value = countdown(today, Date4); document.eventform.count5.value = countdown(today, Date5); document.eventform.count6.value = countdown(today, Date6); } </script> </head> <body onload="setInterval('showCountdown()',100)"> <form name="eventform" id="eventform" action=""> <div id="links1"> <a href="#">Home</a> <a href="#">City Services</a> <a href="#">City Agencies</a> <a href="#">Mayor's Office</a> <a href="#">News Today</a> <a href="#">Upcoming Events</a> </div> <div id="logo"> <img src="logo.jpg" alt="New Years Bash" /> </div> <div id="links2"> <a href="#">Site Map</a> <a href="#">Search Engine</a> <a href="#">Public Notices</a> <a href="#">Survey Form</a> <a href="#">Contact Us</a> <a href="#">E-Government</a> </div> <div id="main"> <h3>Countdown to Upcoming Events</h3> <table> <tr> <td></td> <th style="text-align: right">Current Time </th> <td><input name="thisDay" id="thisDay" readonly="readonly" size="40" /></td> </tr> <tr> <th>Event</th> <th>Starting Time</th> <th>Countdown to Event</th> </tr> <tr> <td><input value="Heritage Day" readonly="readonly" size="20" /></td> <td><input value="Jan 14 at 10:00 am"readonly="readonly" size="20" /></td> <td><input name="count1" id="count1" size="40" /></td> </tr> <tr> <td><input value="Spring Day Rally" readonly="readonly" size="20" /></td> <td><input value="May 21 at 12:00 pm"readonly="readonly" size="20" /></td> <td><input name="count2" id="count2" size="40" /></td> </tr> <tr> <td><input value="July 4th Fireworks" readonly="readonly" size="20" /></td> <td><input value="Jul 4 at 9:00 pm" readonly="readonly" size="20" /></td> <td><input name="count3" id="count3" size="40" /></td> </tr> <tr> <td><input value="Summer Bash" readonly="readonly" size="20" /></td> <td><input value="Sep 1 at 12:00 pm" readonly="readonly" size="20" /></td> <td><input name="count4" id="count4" size="40" /></td> </tr><tr> <td><input value="Holiday Party" readonly="readonly" size="20" /></td> <td><input value="Dec 1 at 11:30 am" readonly="readonly" size="20" /></td> <td><input name="count5" id="count5" size="40" /></td> </tr> <tr> <td><input value="New Year's Bash" readonly="readonly" size="20" /></td> <td><input value="Dec. 31 at 3:30 pm" readonly="readonly" size="20" /></td> <td><input name="count6" id="count6" size="40" /></td> </tr> </table> </div> </form> </body> </html> The external .js file is: Code: /* New Perspectives on JavaScript Tutorial 2 Review Assignment Author: Date: Function List: showDateTime(time) Returns the date in a text string formatted as: mm/dd/yyyy at hh:mm:ss am changeYear(today, holiday) Changes the year value of the holiday object to point to the next year if it has already occurred in the present year countdown(stop, start) Displays the time between the stop and start date objects in the text format: dd days, hh hrs, mm mins, ss secs */ function showDateTime(time) { date = time.getDate(); month = time.getMonth()+1; year = time.getFullYear(); second = time.getSeconds(); minute = time.getMinutes(); hour = time.getHours(); ampm = (hour < 12) ? " am" : " pm"; hour = (hour > 12) ? hour - 12 : hour; hour = (hour == 0) ? 12 : hour; minute = minute < 10 ? "0"+minute : minute; second = second < 10 ? "0"+second : second; return month+"/"+date +"/"+year+" at "+hour+":"+minute+":"+second+ampm; } function changeYear(today, holiday) { year = today.getFullYear(); holiday.setFullYear(year); (holiday < today) ? ++year : year; holiday.setFullYear(year); } function countdown(start, stop) { var time = stop - start; var days = Math.floor(time/(1000*60*60*24); var hours = Math.floor(time/1000*60*60); var minutes = Math.floor(time/1000*60); var seconds = Math.floor(time/1000); return days +"days, "+ hours +"hrs, "+ minutes +"mins, "+ seconds +"secs"+; } If there is any more information that is needed, I will do my best to give that, as well. Thanks! I need help so the specific date & time which the text was saved , appears alongside the text automatically each time a question is asked. It currently just displays the text but NOT DATE OR TIME the text was submitted :/ Thanks a lot in adavance i am just a beginner Here is the coding JSP : Code: <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <body> <%@ page import="java.util.Vector " %> Enter a news story here <form action=Exercise24.jsp method=post> <textarea name="story" rows=5 cols=100></textarea><br> <input type=submit value="Save"><br><br> </form> All news stories: <jsp:useBean id="nl" class="newspackage.NewsStore" scope="application"/> <jsp:setProperty name="nl" property="story"/> <% Vector<String> theList = nl.getStories(); %> <ol> <% for (int i=0; i < theList.size(); i++) { %> <li> <%= theList.elementAt(i) %> </li> <% } %> </ol> </body> Here is the coding in .java: Code: package newspackage; import java.util.Vector; public class NewsStore { Vector<String> stories = new Vector<String>(); public void setStory(String theNews){ stories.addElement(theNews); } public Vector<String> getStories() { return stories; } } Here is the coding to print the specific time WHICH THE QUESTION WAS ASKED: Code: <%@page contentType="text/html" import="java.util.*" %> <!-- http://www.java-samples.com/jsp --> <html> <body> This question was submitted <%= startTime %>. <br> <%! Date startTime = new Date();%> </body> </html> Hello all; I am trying to use two dimensional arrays to create a grid-like slideshow. I have working code for a slideshow using one array, however I was wondering if it is at all possible to move the slideshow in all four directions (instead of just left and right). Here is the code for the left/right slideshow script: Code: <script type="text/javascript"> var present_slide=0; var images = ["../images/overworld/04-8m.png","../images/overworld/04-8n.png","../images/overworld/04-8o.png","../images/overworld/04-8p.png","../images/overworld/04-8q.png","../images/overworld/04-8r.png","../images/overworld/04-8s.png"] objImage = new Image(); function download(img_src) { objImage.src = images[img_src]; } function displaynext(shift) { present_slide = present_slide + shift; if(images.length > present_slide && present_slide >= 0) { document.images["im"].src = images[present_slide]; var next_slide = present_slide + 1; download(next_slide); // Download the next image } if(present_slide + 1 >= images.length ) { document.f1.Next.style.visibility = "hidden"; present_slide = images.length - 1; } else { document.f1.Next.style.visibility = "visible"; } if(present_slide <= 0 ) { document.f1.Prev.style.visibility = "hidden"; present_slide = 0; } else { document.f1.Prev.style.visibility = "visible";} } </script> </head> <body onload="displaynext(0)"> <form name="f1"> <img name="im" /> <div class="arrow-nav"> <input type="button" style="background:url(../images/arrow-left.png);" name="Prev" onClick="displaynext(-1);" /> <input type="button" style="background:url(../images/arrow-right.png); float:right;" name="Next" onClick="displaynext(1);" /> </div> </form> One way that I am thinking that this might work is if I create multiple row arrays and navigate them using up and down arrow keys. So, clicking left and right within the array will navigate through the contained images, and the up and down arrows will navigate through the arrays. Please let me know if this idea can be possibly implemented or if there is another way to do this. Thank you. I have two known methods of creating a javascript array: 1) Double brackets such as: Code: var animation_JD = [[]]; 2) Create and array then create an array inside each array element manually which is the most common method as far as I know. The problem is that the second method requires the array be be defined in size and I require a 2D array, 3D array and 4D array. Using the second method uses far to much memory to be plausible, unless there is a way to make arrays smaller by defining parts of them as integers only? Otherwise for the 1st method I described I don't know how to loop through all elements of the array such as: Code: for(group in animation_JD){ } So does anyone have another way of creating arrays, defining an array as integers only(ideally not every part of the array) to save memory, or a way to loop through arrays created in the first method? Thanks! |