JavaScript - [help] Storing Multi-dimensional Arrays In A Variable
I'm not sure why my code is working. I think it maybe because of incorrect storage of multi arrays.
Can someone please take a look. Please provide advice on how to improve. Code: <script type="text/javascript"> var route ="Route A - Toronto to Barrie"; var jon, don; var businfo=[ //[destination/route, pricing, number of available tickets] ["Route A - Toronto to Barrie", 10.10, 38], ["Route B - Toronto to Peterborough", 12.30, 38], ["Route C - Toronto to Montreal", 42.00, 38], ["Route D - Toronto to Thunder Bay", 114.30, 38] ];//end multi-array businfo function determineRoute() { for(i=0; i < 5; i++){ if (route === businfo[i][0]) { jon = businfo[i]; break; } } } function setNumOfTick(ticketsordered) { don = jon; var tickettotal = don.splice(0,1); tickettotal -= ticketsordered; don.splice(0,1,tickettotal); return(2); }//end setPrice alert(setNumOfTick(35)); </script> Similar TutorialsI 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! Hello, 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 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. Hey all, have a bit of a problem. I'm trying to store a variable in Javascript that consist of user input that may include both quotes and apostraphes (amongst any other stuff). Currently looks a bit like this: Code: <script> var importantNote = [[Note]]; if (importantNote != "" && importantNote != " ") { var importantNoteOutput = "<div class=\"important\"><h3>Important Note:</h3> [[Note]]</div>"; document.write (importantNoteOutput); } </script> Obviously, when [[Note]] (another variable pulled through a seperate program to create complete code) contains ", it doesn't go so well ('[[Note]]' solves that, but creates same issue with any plurals ). I *could* get end user (probably me) to always ensure anything entered in this field (and few others used in a similar way) contain escaped characters, but this isn't preferable. Preferably, I'd like a way of escaping an entire string automatically, eg. encode([[Note]]) - though that doesn't seem to work. Any quick tips? FWIW, I don't think I can use php, or much else for the task. Pretty much stuck with html and javascript. Thanks Basically I am being restricted by a third party program that manages my email list. When a person signs up for my website it first adds them to my external email list and then to my MySQL database. In order to do this you have to pass the information of the form to the next page where you can "display" it. Nothing except this display function seems to work. So what I am trying to do is take what is outputted by this display button and store it in a javascript variable. Then transfer this variable to a form which will auto submit and start the PHP registration. I need help pulling the output of the script, right now I can either get an undefined or the entire HTML code. Is there another option? Here is my code: Code: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd" > <html lang="en"> <head> <title>Raiding Professionals - Register</title> <script type="text/javascript"> var formData = function() { var query_string = (location.search) ? ((location.search.indexOf('#') != -1) ? location.search.substring(1, location.search.indexOf('#')) : location.search.substring(1)) : ''; var elements = []; if(query_string) { var pairs = query_string.split("&"); for(i in pairs) { if (typeof pairs[i] == 'string') { var tmp = pairs[i].split("="); elements[unescape(tmp[0])] = unescape(tmp[1]); } } } return { display: function(key) { if(elements[key]) { document.write(elements[key]); } else { document.write("<!--If desired, replace everything between these quotes with a default in case there is no data in the query string.-->"); } } } }(); </script> </head> <body> <div id='1'><script type="text/javascript">formData.display("name (awf_first)")</script></div> <div id='2'><script type="text/javascript">formData.display("name (awf_last)")</script></div> <div id='3'><script type="text/javascript">formData.display("email")</script></div> <div id='4'><script type="text/javascript">formData.display("custom password")</script></div> <form method='post' action='register.php' name='register'> <input name='firstname' id='firstname' value='' type='text'> <input name='lastname' id='lastname' value='' type='text'> <input name='email' id='email' value='' type='text'> <input name='password' id='password' value='' type='password'> <input name='password2' id='password2' value='' type='password'> <input type='submit' value='submit'> </form> <script type='text/javascript'> var firstname = document.getElementById('1').innerHTML; ; var lastname = document.getElementById('2').innerHTML; ; var email = document.getElementById('3').innerHTML; var password = document.getElementById('4').innerHTML; ; document.getElementById("firstname").value = firstname; document.getElementById("lastname").value = lastname; document.getElementById("email").value = email; document.getElementById("password").value = password; document.getElementById("password2").value = password; </script> </body> </html> Hey, Say I've got a variable with a load of arrays in it ... Code: questions = [ ["<Question1> Question", "choice1","choice2", "choice3"], ["<Question2> Question", "choice1","choice2", "choice3"], ["<Question3> Question", "choice1","choice2", "choice3"], ["<Question4> Question", "choice1","choice2", "choice3"], ... ["<Question11> Question", "choice1","choice2", "choice3"], ... ] And in a textbox called 'ShowAllQuestions' I want to list all the questions in order (but without showing the choices (answers) along with them). How would i go about doing this? Would I need to sort the arrays first? If so, its tricky because '11' would come before '2' in this case.. I need to loop the alphabet and numbers 0-9 to initialize a few thousand arrays. This is for my site and is truly needed. http://www.thefreemenu.com I currently have every array written out and it takes up to much space in my .js file. The majority of my variables are empty but necessary and need to be there (including empty) for my site to work properly. Question is the last part Here's where I'm at. Code: var NewVarLetterOrNum = "a"; eval("_oneofseveralnames_" + NewVarLetterOrNum + "='this part works';"); alert(_oneofseveralnames_a); This creates the variable _oneofseveralnames_a='this part works' Code: var newArrayLetterOrNum = "a"; eval("_oneofseveralnames_" + newArrayLetterOrNum + "= new Array();"); alert(_oneofseveralnames_a) This creates the Array _oneofseveralnames_a=new Array(); and all the values in the array are null, but, now a variable like _nl_a[1]='something' can be used elsewhere because the array exists. This is all that is necessary for now because I can probably set all the variables to be blank with something like Code: i=1 while(i<=20){ _oneofseveralnames_a[i]="1-20"; i++ } alert(_oneofseveralnames_[20]); So now you have what I came to understand in the first few hours. Now to the hard part : ( I can't make multiple array's dynamically. I dont' know if its because I don't understand loops or arrays or what and its very fustrating. As for any answer you might be so kind as to provide, if you could dumb it down that would be greatly appreciated. Code: var newArray =new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z') i=1 while(i<=26){ eval("_nl_" + newArray[i] + "= new Array();"); i++ } alert(newArray[1]) // Is b, but alert(_nl_b) //I can't get _nl_b to exist, I tried everything including taking away the quotes around the letters in every test */ var _nl_a =new Array() var _img_a =new Array() var _h_a =new Array() var _r_a =new Array() var _m_a =new Array() var _yt_a =new Array() var _i_a =new Array() The above arrays are all the array _name_ parts I need but for example, a has 10 parts, a,p2_a,p3_a,.. p10_a. I need 10 pages for each letter of the alphabet and numbers 0-9 and a special all1, p2_all1 ... p10_all1. Overall 2200 arrays that need to be declared. Currently they are all written out. /* 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 I'm trying my hand at localstorage (which is HTML5), but I'm combining it with javascript (which is... erm, well, javascript ) so I decided to put this in the javascript forum. If I'm wrong, I apologize. Anyway, though I'm not a complete newbie when it comes to coding, this is new for me and frankly, I'm stuck. What I'm trying to do (nothing special, just messing around a bit) is show the current time and the time the visitor last visited. I made this: Code: var tijd = new Date(); var oudetijd = tijd.getTime(); localStorage.setItem('laatste bezoek', oudetijd); var laatstebezoek = localStorage.getItem('laatste bezoek'); document.write(laatstebezoek + "<br>"); document.write(oudetijd); Should work, right? Well, it does... partly. It shows the current time (woohoo!!! ) but the "old time" (oudetijd) is exactely the same! Now, I know I'm doing something wrong here, most likely something stupid like a missing comma, but whatever it is, I don't see it. Can someone shed some light on this? P.S. As you can probably see from the code, I'm Dutch. I dont know if it helps or not, but here's a translation: tijd= time oude tijd = old time laatste bezoek = last visit Thanks in advance! Hey All, I have completed most of a homework assignment that I am working on. I am able to .push desired elements into an array: Code: //Insert variable into the Array function insertElem(){ //Insert and sort first array, but not second array if(nameInput.value != ""){ studName2.push(nameInput2.value); } else{ alert("Value to be inserted cannot be Null"); } //Refresh display area clearAndShow2(); } What I would like to do is be able to store and display the created array "permanently" until I decide to remove the elements. My current method to hold the elements, until the page is refreshed, is: Code: //Refresh second array function clearAndShow2(){ nameInput2.value = ""; messageBox2.innerHTML = ""; messageBox2.innerHTML += "Groups: " + "<br />" + studName2.join("<br />") + "<br />"; } I appreciate the assistance. Hi all I am trying to create a code which stores information about songs The information to be stored are : song ID song name song artist song URL So far what I've done is create an empty array with four properties The code asks the user to enter information and then displays them However i'm having difficulty figuring out how to insert all the information entered in the array. For example if information about 3 songs were entered, how can I insert all of them in the array I created. After storing the information, I want to be able to search for songs by their ID. When I wrote the function to do this, if lets say I entered two songs one with S1 as ID and one with S2 as ID, I type S1 in the search box, but it doesn't return anything. However if I enter S2, it returns the information of the track with this ID, which makes me think that entering information for a second song overwrites the first one This is my code so far: <html> <body> <h1>Tracks and Artists</h1> <script type="text/javascript"> function request(tracks) { for (var i=0;i<2;i++) { tracks.trackID = prompt("Enter track ID") tracks.trackName = prompt("Enter track name") tracks.trackArtist = prompt("Enter artist name") tracks.trackURL = prompt("Enter track URL") alert(display(tracks)) } } function insert() { function display(tracks) { return "Track ID: " + tracks.trackID + "\nTrack name: " + tracks.trackName + "\nTrack artist: " + tracks.trackArtist + "\nTrack URL: " + tracks.trackURL } var tracks = [{trackID: "", trackName:"", trackArtist:"", trackURL:"" }] request(tracks) </script> </body> </html> Hey guys, I just recently started getting into JavaScript (2 days ago) after seeing how limited HTML and CSS by itself is, and I created a game where you have a certain amount of time to click as much as you can. The game works fine but the problem is with my leaderboard. I want to be able to store the high scores and names so that everybody see's the same thing. I know cookies save data but is that only clientside? All I need to do is save 6 variables so that the leaderboard is always updated. Any help would be appreciated. Thanks. Hello, I hope someone can help. I know on the front end using js you can get the date and time on client machine and store in a hidden field so it can be grabbed to use on the back-end to store in a database or even return a special message based on their time. However, I'm not too sure how to begin. Would anyone happen to have any idea on how to do this? Thanks in advanced! Hi all, ok firstly i know all but nothing about javascript and you prob about to see the worst attempt eva at trying to understand it ok so here is my js code Code: <script language="javascript"> function selectElement(idElement) { var ratingval = ""; liElement = document.getElementById('sel'+idElement); lirating = document.ratingform.userrating.value; if(liElement == "sel1") { raingval = "1"; lirating = "1"; } if(liElement == "sel2") { raingval = "2"; lirating = "2"; } if(liElement == "sel3") { raingval = "3"; lirating = "3"; } if(liElement == "sel4") { raingval = "4"; lirating = "4"; } if(liElement == "sel5") { raingval = "5"; lirating = "5"; } } </script> and here is my html code Code: <form name="ratingform" action="" method="post"> <fieldset class="login"> <legend>Personal Details</legend> <div> <label for="fname">First Name</label> <input type="text" id="fname" name="fname" value="<?php if(isset($_POST['fname'])){ echo $_POST['fname'];}?>"> </div> <div> <label for="lname">Surname</label> <input type="text" id="lname" name="lname" value="<?php if(isset($_POST['fname'])){ echo $_POST['lname'];}?>"> </div> </fieldset> <fieldset class="contact"> <legend>Review</legend> <div> <label for="title">Review Title</label> <input type="text" id="title" name="title" value="<?php if(isset($_POST['title'])){ echo $_POST['title'];}?>"> </div> <div> <label for="review">Review</label> <textarea name="review" id="review" cols="33" rows="5"><?php if(isset($_POST['review'])){ echo $_POST['review'];}?></textarea> </div> </fieldset> <fieldset class="rating2"> <legend>Rating</legend> <div> <label for="rating">User Rating</label> <ul class="rating"> <li id="current" class="current" style="width: <?php echo $_GET['rating']?>em;"></li> <li id="sel1"><a onclick='onClick="javascript:selectElement(1)' class="rate1" title="I hated it">*</a></li> <li id="sel2"><a href="?rating=2" class="rate2" title="I disliked it">*</a></li> <li id="sel3"><a href="?rating=3" class="rate3" title="It was OK">*</a></li> <li id="sel4"><a href="?rating=4" class="rate4" title="I liked it">*</a></li> <li id="sel5"><a href="?rating=5" class="rate5" title="I loved it">*</a></li> </ul> </div> </fieldset> <div> <input type="hidden" name="userrating" value="" /> <input type="submit" name="Submit" value="Submit"><?php if($error == TRUE){echo $message;}if($submit == TRUE && $error == FALSE){echo $message;}?></div> </form> ok so what im trying to acheive is that when a user clicks on either of the rating links, a js function is run which gets the li value and then sets a value of a varible to match the li value and then i want to add that value to the hidden userrating form input and set the value of <li id"current" width value to the same value but as im sure youve noticed from my code it isnt working. any help it greatly needed and appreciated, thanks Luke Hi everyone, The website that I am trying to create has a couple of drop down lists. I want a variable to store the value (text) of the data field selected from a particular drop down list. Let me explain this with an example: If a dropdown list has data fields like (aa, bb, cc, dd, ee) and if a user selects the option 'bb' , then there should be a variable that stores the text 'bb'. I am using the following piece of code. Can you please take a look at it to tell whether I am doing the correct thing or not. Firstly, the HTML code that generates the drop down list on the page. This works fine. Code: <b> Student's Profession</b> <FORM NAME="Profession"> <SELECT NAME="Student’s Profession"> <OPTION VALUE="k1">Select <OPTION VALUE="k2">Engineer <OPTION VALUE="k3">Doctor <OPTION VALUE="k4">IAS <OPTION VALUE="k5">Lawyer <OPTION VALUE="k6">CA <OPTION VALUE="k7">IAS <OPTION VALUE="k8">Engineer + MBA <OPTION VALUE="k9">Family Business <OPTION VALUE="k10">None of the above </SELECT> </FORM> [Then I have declared a function in JavaScript that stores the value of the data field selected in a particular variable (sel_student_profession). I am not sure about the parameter. Should I simply write 'dropdown' or write the form name? (Profession). Or something else? Code: <script type="text/javascript"> function Selected_profession(dropdown) { var myindex = Profession.selectedindex; var sel_student_profession = Profession.options[myindex].text; return sel_student_profession; } </script> And then at the end of it, if I want to know the value (text) of the data field selected, I call the function. Right now, I am calling the function as follows: Code: var student_profession = Selected_profession(Profession); So, if the user selects "engineer" from the drop down list, student_profession should store "engineer". Am I doing it the correct way? If not, I would highly appreciate any sort of help. Thanks a lot! I'm integrating a JavaScript typing tutorial to my website. But I'm not able to store the value to the database. In the below code you can see the speed is updated in a html span. The id of the tag is speed(<span id="speed"></span>). This code will automatically update when user start typing. I want to update this to a database when user press submit button. But i cant able to. Is there any way to input the speed to database ? Please go through the below code and suggest me what i can do....? Code: <script type="text/javascript"> //<![CDATA[ var garray = new Array(); var garrayIndex = -1; var gtext = ""; var gindex = 0; var goldPressed = 0; //previous pressed key code var goldTarget = 0; //previous target key code var gtarget = 0; var gpressed = 0; var ggood = 0; var gtotal = 0; var gtime = 0; var gkeytime = 0; function setup() { setEvents(); //change this array to suit your needs but note that indices //must ascend by 1 from 0: garray[0]="foo"; garray[1]="bar";... garray[0] = "a s d f s d f f s d as sd ad fs ds sad af sa fa dafa sda dad das afa sfd add sasd df sf saf dds fd ads safd fsd fas sas dafs as fad"; //more similar lines can easily be added above, dont forget to get the index right! garrayIndex = -1; next(); } function setPatternInit() { //#b note: once we did this using innerHTML but this caused //a leakage of handles in ie var pat = document.getElementById("pattern"); for(; { if (pat.hasChildNodes()) { pat.removeChild(pat.lastChild); } else break; } var cname = "done"; for (j=0; j<gtext.length; j++) { var ch = gtext.charAt(j); if (j>gindex) cname = "future"; else if (j==gindex) cname = "todo"; var kid = document.createElement("span"); kid.className = cname; var txt = document.createTextNode(ch); kid.appendChild(txt); //#b innertext doesnt work on firefox pat.appendChild(kid); } } function setPattern() { var pat = document.getElementById("pattern"); var kids = pat.childNodes; var cname = "done"; for (j=0; j<gtext.length; j++) { if (j>gindex) cname = "future"; else if (j==gindex) cname = "todo"; var kid = kids[j]; kid.className = cname; } } function mapToBoard(code) { if ((code>=97)&&(code<=108)) return (code-32); if ((code>=110)&&(code<=122)) return (code-32); if ((code>=65)&&(code<=90)) return code; if ((code>=48)&&(code<=57)) return code; if ((code==32)) return code; if ((code==44)||(code==46)||(code==47)||(code==59)) return code; return 0; //not on our board picture } function setBoard() { var letter; var elt; var c; var s; if (goldTarget!=0) { c = mapToBoard(goldTarget); if (c!=0) { letter = "code"+c; elt = document.getElementById(letter); s = "silent"; elt.className = s; } } if (goldPressed!=0) { c = mapToBoard(goldPressed); if (c!=0) { letter = "code"+c; elt = document.getElementById(letter); s = "silent"; elt.className = s; } } if (gtarget!=0) { c = mapToBoard(gtarget); if (c!=0) { letter = "code"+c; elt = document.getElementById(letter); s = "target"; elt.className = s; } } if (gpressed!=0) { c = mapToBoard(gpressed); if (c!=0) { letter = "code"+c; elt = document.getElementById(letter); s = "pressed"; elt.className = s; } } } function nextPattern() { goldTarget = gtarget; goldPressed = gpressed; if (++garrayIndex == garray.length) garrayIndex = 0; gtext = garray[0]; gindex = 0; gpressed = 0; setPrompt(); } function prevPattern() { goldTarget = gtarget; goldPressed = gpressed; if (--garrayIndex < 0) garrayIndex = garray.length - 1; gtext = garray[garrayIndex]; gindex = 0; gpressed = 0; setPrompt(); } function next() { nextPattern(); setPatternInit(); setBoard(); } function prev() { prevPattern(); setPatternInit(); setBoard(); } function skip(e) { next(); return false; } function back(e) { prev(); return false; } function setEcho(c, isOK) { var s; if (c<' ') c=' '; var s = "["+c+"]"; if (!isOK) s += " ..OOPS!" var elt = document.getElementById("echo"); var txt = document.createTextNode(s); //#b if (elt.hasChildNodes()) { elt.replaceChild(txt, elt.lastChild); } else elt.appendChild(txt); } function setPrompt() { var ch = gtext.charAt(gindex); gtarget = ch.charCodeAt(0); } function adjustStatistics(ch) { return; //could count errors by character } function updateSpeed(ok) { var t = (new Date()).getTime(); var dt = (t-gtime); gtime = t; if (dt > 5000) return; //ignore sleepy user gkeytime += dt; var s = (0.5+ggood*60*200/gkeytime).toFixed(0) + ""; var elt = document.getElementById("speed"); var txt = document.createTextNode(s); //#b if (elt.hasChildNodes()) { elt.replaceChild(txt, elt.lastChild); } else elt.appendChild(txt); } function updateScore(ok) { if (ok) ggood++; gtotal++; updateSpeed(ok) var s = ggood.toFixed(0) + ""; var elt = document.getElementById("count"); var txt = document.createTextNode(s); //#b if (elt.hasChildNodes()) { elt.replaceChild(txt, elt.lastChild); } else elt.appendChild(txt); s = (gtotal-ggood).toFixed(0) + ""; elt = document.getElementById("accuracy"); txt = document.createTextNode(s); //#b if (elt.hasChildNodes()) { elt.replaceChild(txt, elt.lastChild); } else elt.appendChild(txt); var s = (gkeytime/1000).toFixed(2) + " s"; var elt = document.getElementById("time"); var txt = document.createTextNode(s); //#b if (elt.hasChildNodes()) { elt.replaceChild(txt, elt.lastChild); } else elt.appendChild(txt); } function reset(e) { window.location.reload(); } function debug() { //#b to use, set body onLoad="debug()" instead of "setup()" in html //document.onkeydown=debugKey; //#b document.onkeypress=debugKey; } function debugKey(evt) { //#b var e = (window.event) ? window.event : evt; //#b var k = (e.which)? e.which : e.keyCode; var f = filterKeyCode(k); var s = "k="+k+",f="+f; alert(s); return false; } function setEvents() { //#b document.onkeydown=down; //#b document.onkeypress=press; (document.getElementById('skip')).onmousedown=skip; (document.getElementById('back')).onmousedown=back; (document.getElementById('reset')).onmousedown=reset; } function cleanup() { //pointless, really document.onkeydown=null; //#b document.onkeypress=null; (document.getElementById('skip')).onmousedown=null; (document.getElementById('back')).onmousedown=null; (document.getElementById('reset')).onmousedown=null; } function filterKeyCode(code) { //from key down (0 to ignore) //note: user must have num lock set if they want to use keypad numbers if ((code>=65)&&(code<=90)) return code; //alpha if ((code>=48)&&(code<=57)) return code; //numberic if (code==32) return code; //blank if ((code>=96)&&(code<=105)) return code; //number pad digits if ((code==13)||(code==16)) return code; //enter, shift if ((code>=106)&&(code<=111)) return code; //number pad operators if ((code>=186)&&(code<=192)) return code; //punctuation if ((code>=219)&&(code<=222)) return code; //punctuation return 0; } function filterCode(code) { //from key press as ascii char code (0 to ignore) if ((code==13)||(code==16)) return code; //enter and shift are allowed if (code<32) return 0; if (code>=127) return 0; return code; } function capsLockFilter(e, pressed) { //#b many problems making this cross browser! //#b e.modifiers known only on early mozilla (which does not know standard e.shiftkey)? var shifted = e.shiftKey || (e.modifiers && (e.modifiers & Event.SHIFT_MASK)); //#b var locked = (((pressed > 64) && (pressed < 91) && (!shifted)) || ((pressed > 96) && (pressed < 123) && (shifted))); if (locked) alert("caps lock!"); } function down(evt) { //#b var e = (window.event) ? window.event : evt; //#b var rawcode = (e.which)? e.which : e.keyCode; pressed = filterKeyCode(rawcode); if (pressed > 0) return true; if (typeof(e.cancelBubble)!="undefined") e.cancelBubble = true; if (typeof(e.stopPropagation)!="undefined") e.stopPropagation(); return false; //#b nuisance keys - backspace etc on ie (no effect for capslock!!) } function press(evt) { //#b //#b should work in ie, firefox, safari(hopefully), opera(hopefully) var e = (window.event) ? window.event : evt; //#b var pressed = 0; var wc = -1; var kc = -1; var cc = -1; if (typeof(e.keyCode)!="undefined") kc = e.keyCode; //ie if (typeof(e.charCode)!="undefined") cc = e.charCode; //firefox if (typeof(e.which)!="undefined") wc = e.which; //old mozilla if ((kc>=0)&&(cc>=0)) { //firefox pressed = cc; } else if (kc>=0) pressed = kc; //ie else if (wc>=0) pressed = wc; //old mozilla //alert("pressed="+pressed+",kc="+kc+",cc="+cc+",wc="+wc); pressed = filterCode(pressed); if (pressed==0) { if (kc==13) return skip(); //#b firefox else return false; } if (pressed==13) return skip(); //#b ie capsLockFilter(e, pressed); //hmm var c = String.fromCharCode(pressed); //ie from ascii code var ch = gtext.charAt(gindex); var ok = (c==ch); goldPressed = gpressed; gpressed = pressed; goldTarget = gtarget; if (ok) { gindex++; if (gindex==gtext.length) { if (gtotal-ggood <= 5 && 0.5+ggood*60*200/gkeytime >= 20) { alert('Good work! You had fewer than 5 errors and typed faster than 20 WPM! Now try the next exercise!'); setPatternInit(); } else if (gtotal-ggood > 5 && 0.5+ggood*60*200/gkeytime >= 20){ alert('Good speed! You were over 20 WPM but have more than five errors! Slow down a bit for accuracy.') setPatternInit(); } else if (gtotal-ggood <= 5 && 0.5+ggood*60*200/gkeytime < 20){ alert('Good accuracy! You had fewer than 5 errors, now try for 20 WPM.') setPatternInit(); } else alert ('Focus on accuracy first, then go for speed!'); setPatternInit(); } else setPattern(); gpressed = 0; setPrompt(); setEcho(c, true); updateScore(true); } else { setEcho(c, false); updateScore(false); setPattern() } setBoard(); return false; } //</XMLCDATA> </script> This is my HTML Code : Code: <body onload="setup()" onunload="cleanup()"> <div id="container1"> <div id="container3"> <div id="body"> <div id="pattern" class="big"> </div> <div id="prompt" class="prompt"> </div> <div id="board" class="board"> <div id="row0" class="row0"> <span id="code49">1</span> <span id="code50">2</span> <span id="code51">3</span> <span id="code52">4</span> <span id="code53" style="margin-left:-5px;">5</span> <span id="code54">6</span> <span id="code55">7</span> <span id="code56">8</span> <span id="code57">9</span> <span id="code48">0</span> </div> <div id="row1" class="row1"> <span id="code81">Q</span> <span id="code87">W</span> <span id="code69">E</span> <span id="code82" style="font-weight:bold">R</span> <span id="code84">T</span> <span id="code89">Y</span> <span id="code85" style="margin-left: -2px;">U</span> <span id="code73">I</span> <span id="code79">O</span> <span id="code80">P</span> </div> <div id="row2" class="row2"> <span id="code65">A</span> <span id="code83">S</span> <span id="code68">D</span> <span id="code70" style="font-weight:bold;">F</span> <span id="code71" style="margin: 0 0 0 -5px;">G</span> <span id="code72">H</span> <span id="code74" style="font-weight:bold;">J</span> <span id="code75">K</span> <span id="code76">L</span> <span id="code59">;</span> </div> <div id="row3" class="row3"> <span id="code90">Z</span> <span id="code88">X</span> <span id="code67">C</span> <span id="code86" style="font-weight:bold">V</span> <span id="code66">B</span> <span id="code78">N</span> <span id="code77" style="font-weight:bold">M</span> <span id="code44">,</span> <span id="code46">.</span> </div> <div id="row4" class="row4"> <span id="code32">[SPACE]</span> </div> <div id="scores"> <div class="count">Characters: <span id="count"></span> </div> <div class="accuracy">Errors: <span id="accuracy"></span> </div> <div class="speed">WPM: <span id="speed"></span> </div> <div class="time">Time: <span id="time"></span> </div> </div> <div align="center"> <button id="reset" class="button123" name="reset" align="center">Restart Exercise</button> </div> </div> <div id="echo" class="echo" style="display:none;"> [] </div> <div style="display:none;"> <button id="skip" class="button123" name="skip">skip</button> to next line ("enter" key is shortcut) </div> <div style="display:none;"> <button id="back" class="button123" name="back">back</button> to previous line </div> </div> </div> hey guys im not new to javascript but arrays still confuse me exspecialy when put into loops ok say i had 2 arrays i have used jquerry to extract a question lets say this is the question How long is a piece of string? the answer is for this example infinite so what i want to do is search the question trough a array with 21984 and more in the future when it finds the match it then looks at the answers array at the same array length as where the question was found then sends the answer to a variable for later use could someone give me a example on how to do this please? Hi, I have a programing problem that have been around for ages. I have search on google using several expressions and words and after hours of digging i'm still unable to do it. I would like to get a value from a HTML page hosted remotely with an inconstant value. Then define this value and name as a javascript variable and apply or show in my page. Thanks for all the help P.S. Is there any way to make a domain lookup in javascript? I mean a user enters a domain and the script converts to an ip and shows to the user. If not thanks, probably it can only be done in the server side... Hi there, I have a couple of scripts which both do exactly what I want, but when I try use them both at the same time only one of them will work, could you tell me if i need to change anything in them to get them both to work at the same time or if im missing something really simple? Thanks Script 1 Code: <script type="text/javascript"> var imgPaths = ['pic1.jpg', 'pic2.jpg', 'pic3.jpg', 'pic4.jpg', 'pic5.jpg']; //preload the images var imgObjs = new Array; for(var i=0; i < imgPaths.length; i=i+1) { imgObjs[i] = new Image(); imgObjs[i].src = imgPaths[i]; } function togglePic(num) { if(currPic == 0 || currPic != num) { document.getElementById("image").src = imgObjs[num].src; currPic = num; } else { document.getElementById("image").src = imgObjs[0].src; currPic = 0; } } //load the default image window.onload=function() { document.getElementById("image").src = imgObjs[0].src; currPic = 0; //flag storing current pic number } </script> Script 2 Code: <script type="text/javascript"> window.onload=function () { setStyles(); }; function setStyles() { ids = new Array ('style1','style2','style3','style4'); for (i=0;i<ids.length;i++) { document.getElementById(ids[i]).className=''; document.getElementById(ids[i]).onclick=function() { return Cngclass(this); } } } function Cngclass(obj){ var currObj; for (i=0;i<ids.length;i++) { currObj = document.getElementById(ids[i]); if (obj.id == currObj.id) { currObj.className=(currObj.className=='')?'selected':''; } else { currObj.className=''; } } return false; } </script> HTML Code: <!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title></title> </head> <body> <div id="style"> <div id="styleimage"> <img src="" id="image" width="610" height="229" /> </div> <div id="stylenav"> <ul> <li id="style1"><a href="#" onclick="togglePic(1); return false">style 1</a></li> <li id="style2"><a href="#" onclick="togglePic(2); return false">style 2</a></li> <li id="style3"><a href="#" onclick="togglePic(3); return false">style 3</a></li> <li id="style4"><a href="#" onclick="togglePic(4); return false">style 4</a></li> </ul> </div> </div> </body> </html> |