JavaScript - Stuck On Javascript Arrays (getting Confused)
Hi there coding friends,
im stuck again this time on arrays.. Im trying to get my head around it and im sure it's one of those things you do once you know what your doing (to an extent) now the problem is... i have 2 arrays for a experiment one = flowerheight and the other is flowernumbers. now the height is set out as 15,16,17,18,19 and numbers 2,1,6,4,2 what the aim is in the first part is to times the height by numbers of the corresponding array ie. 15x2 16x1 17x6 18x4 19x2 to make a 3rd array with them as the totals then the second part of the program is to calculate the average height i.e total of total of numbers array (2+1+6+4+2) + total of 3rd array(15x2+16x1+17x6+18x4+19x2) then a write to show what the total was.. now all I have of the code is... Code: <HTML> <HEAD> <TITLE> Flower Experiment </TITLE> <SCRIPT LANGUAGE = "JavaScript"> /* * Program to calculate average height of flowers.. */ //Experiment results var flowerHeights = [15,16,17,18,19]; var flowerNumbers = [2,1,6,4,2]; //Write code to work out and show flowerheightxnumbers. //Write code to calculate the average height of the flowers (total of flowernumbers + (flowerheight X numbers) and write it out in the browser window. </SCRIPT> </HEAD> <BODY> </BODY> </HTML> now I have no idea how to go about this it's making me loose my mind. Can someone start me off in the right directon and/or explain to me what to do. Anyhelp much appreciated, I wish I could have done more to the question to make it easier for you lot to help me but my brain is frazzled Thanks. James Similar TutorialsThis has been resolved. The moment i posted it i realised the mistake i was making . Learnig how to delete my post, until then thought i would sdimply delete the content.
Any suggestions on how the javascript below should be changed so it will work with checkboxes that have brackets in the name? (I'm using foreach in php, and can't seem to get the php to work/work correctly without using them.) Thanks! Code: function chktotal(j) { var total=0; for (var i=0; i < document.form1.ckbx.length; i++){ if(document.form1.ckbx[i].checked){ total=total+1; } if(total>8){ alert("Please only select 8"); document.form1.ckbx[i].checked = false; total = total -1; return false; } } document.form1.totalval.value = total; } <input onclick="chktotal(2)" value ="Sample Item 1" type="checkbox" name="ckbx[]"> hey guys i have the following code that extracts the information from the questiondiv then i have a for loop to search the array but it keeps returning it has no answer can someone help me please and i know im most probly doing somthing realy silly wrong. P.S some reason the codes indenting got messed up when i pasted it here Code: <html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> <script> function code() { function getNodes(prop, val, meth, nd, useSelf ) { var r=[], any= getNodes[val]===true; nd=nd||document.documentElement; if(nd.constructor===Array){nd={childNodes:nd};} for(var cn=nd.childNodes, i=0, mx=cn.length;i<mx;i++) { var it=cn[i]; if( it.childNodes.length && !useSelf ){r=r.concat(getNodes(prop, val, meth, it,useSelf ));} if( any ? it[prop] : (it[prop]!==undefined && (meth ? ""[meth] && String(it[prop])[meth](val) : it[prop]==val))){ r[r.length]=it; } }//nxt return r; };getNodes[null]=true;getNodes[undefined]=true; //end getNodes() var answer; trivia = new Array('test?','test1'); var triviaGet = getNodes( "data", //examine each node's .data property (only hits text nodes) /\?/, //looking for text with a "?" "match", //using String().match method to accept arguments[1] document.getElementById("questiondiv") // looking in the question div )[0].textContent.split("?")[0]+"?" //show text of first match alert(triviaGet); var i=0; var answer1; var answer2; for(i=0; i < 8400; i++) { if(trivia[i] == triviaGet) { answer = trivia[i]+1; document.getElementById("test").innerHTML=(answer) break; } else { document.getElementById("test").innerHTML=("Answer not found!"); } } //search trivia array for match to question //when found the answer is the next one in the array so if it finds the question at index 7261 then the answer is in index 7262 // TODO: insert answer into text box... } </script> </head> <body> <div style="display: none;" id="questiondiv"> You challenge The Wiseman to a game of trivia, he asks you this question:<br/> <br/> test?<br/> <br/> <input class="dungeoninput" type="text" size="16" id="answer" value="" maxlength="32"></input><br/> <div class="btn100" style="margin-top: 6px;" onclick="loadDiv2('/dream/explore?action=acceptTrivia&qid=727'); return false;">Answer</div> </div> <div id="test"> test </div><br /> <button value="code()" onclick="code()">click me</button> </body></html> Ok so this is probably a simple question but i have hit a wall he So I have 20 arrays with incremental names (course1, course2, course3 ...) What i want to make is a selection box with 20 options. for each option the value would be course1[0] and the text shown would be course1[1]. if i write this code: <code> for (var i=1; i<=20; i++){ var select = document.getElementById("selectiontest") select.options[select.options.length] = new Option (course1[1], course1[0]) } </code> The code works and the correct array values are put as the option text and value. I am having trouble getting the loop to move from course1 to course2, i used the loop counter in the array name like this: <code> for (var i=1; i<=20; i++){ var select = document.getElementById("selectiontest") select.options[select.options.length] = new Option (('course'+i)[1], ('course'+i)[0]) } </code> this is where it stops working. I get 20 values of o. which i assume is the second character of course. How do i tell javascript to incrementally change the array name during the loop? Hi, I'm kinda newbie in javascript and would really like some help if you wouldn't mind? I'm working with dreamweaver and VBScript and have drop down lists being populated by dynamic recordsets, the tables that are being used are text fields and everything is working fine other than one niggly thing I want to do and just don't seem to be able to get the javascript code right The data I have has two columns; area and technical issue. As the area contains duplicates I have this as a separate drop down list with a distinct in the sql command and from an onclick event from the 'area' drop down list, I get the value of the selected item [var x = document.NewFacilityAdminDetailsTest.ara_component.selectedIndex; var ara_component = document.NewFacilityAdminDetailsTest.ara_component.options[x].value;] all's well so far.... The second drop down list contains all the 'technical issues' which is great, BUT because its a dynamic recordset its for ALL of the areas and I want to be able to take away the technical issue values in the technical issues drop down list that don't belong to the area that's been picked and I also dont' want the user selecting a technical issue that isn't linked of the area. I've tried some of the samples I've found by googling and even the adobe example but they all seem long winded and I never quite get the code right and the second drop down list just keep showing ALL 'technical issues show' for ALL of the 'areas'. Surely there's a bit of javascript to turn the second drop down list recordset into an array, loop through the array and remove the technical issues that don't match the selected value from the 'area' drop down list and put the array into the second drop down list instead of using the recordset? Any help would be soooooo useful. Best Regards Joan, Cheshire Hi i am confused in one topic and need help, I have a javascript array containing objects like; Object values are ordered as Type, Amount and count. Object 1 => ("A" , 100 ,10) Object 2 => ("C" , 50 ,10) Object 3 => ("A" , 100 ,20) Object 4 => ("B" , 200 ,10) Object 5 => ("A" , 10 ,10) Object 6 => ("B" , 100 ,10) Object 7 => ("C" , 100 ,5) Object 8 => ("C" , 50 ,5) In the end i want to group these objects like ; ("A" , 100,30) (Note : 30 = 20 +10) ("A" , 10,10) ("B" , 200,10) ("B" , 100,10) ("C" , 100,5) ("C" , 50,15) 15 = 10 + 5 How can i do this in javascript, note that the new types will be added to this array ? Hello guys, I'm new to this forum and to Javascript. I need to make a very simple website to check whether a ticket number is valid or not. I have created an array with all the codes necessary, but when I try to loop through it, the only thing that works as it should is the first element of the array. Basically, I want the code to display Correct!, if there is a match between user input and array, or Wrong if otherwise. Here is my code: Code: <!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>Untitled Document</title> <script type="text/javascript"> function validate() { var list = new Array; list[0]="zDv5BXAc"; list[1]="6YXF3Qwj"; list[2]="k8UKpgwo"; var code= document.getElementById("code"); var name = document.getElementById("name"); for(var i=list.length-1; i>=0; --i) { if (code.value == list[i]) { document.all.confirm.innerHTML = "Correct" } else document.all.confirm.innerHTML = "Wrong" } } </script> </head> <body> <input name="Name" type="text" id="name" size="50"> <input name="Code" type="text" id="code" size="10"> <input name="Check Code" type="submit" value="Verify" onClick="validate()"> <div id="confirm"></div> </body> </html> 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! Hi everyone, i am stuck at a problem. i am trying to craete a redimmensionable array using javascript, is there a way to do this, i know that this can be done in vbscript using redim and preserve commands. If not then is it possible to variables between javascript and vbscript, or call vbscript function using javascript. a sample code will be much aprreciated thanks for your time! J Hello, I very new to this language and I still feel like I'm not grasping it... But, anyways, I'm doing a thing for school and I have to let the user input a string. I need to save the string and turn it into an array. For every word that is less than five letters I put "little" at the beginning of the word and for every word that is more than five letters I put "big" at the end of each word. Then I need to return the new string into output. I think I wrote the code really incorrectly, so any tips/advice would be much appreciated! Also, I don't understand adding user input into a code if that makes sense. The tutorials/lessons I've been looking at all say to put information into an array first and then mess with it. But, what if you don't have information in the array until the user puts it in? And once they enter it, then you mess with what they entered. I can't seem to get how to do that. Thank you for your time Code: function texter(newText){ var oldHTML = document.getElementById('outputPrompt').innerHTML; document.getElementById('outputPrompt').innerHTML = newText+"<br />"+oldHTML; console.log(newText); } function menuTwo(){ var userInput = document.getElementById('input').value; var correctedInputArray = userInput.toLowerCase().split(" "); var mainTwo = new Array([""]); for(var i=0; i<correctedInputArray.length; i++){ var thisWord = correctedInputArray[i]; var lessFive = 5; var moreFive = 6; var restOfWord; if(lessFive<5){ mainTwo[i]=thisWord+"-little"; }else if(moreFive>6){ mainTwo[i]="big-"+thisWord; } else{ restOfWord = thisWord.substr(1, thisWord.length-1); } } output = mainTwo.join(" "); texter(output); } </script> </head> <body> <h1>Document</h1> <input type='text' id='input' /> <input type='button' onclick='menuTwo()' value='submit'/> <p id='outputPrompt'>Please enter 1,2,3 or exit only</b> </p> </body> </html> I'm working on this website and some contents are set up in arrays. How do you refer variables to work with arrays. I need the correct syntax.
I'm trying to do this using numerical arrays for an assignment: Create a webpage with three select boxes. If basketball is selected in the first select box, the second select box should display the names Celtics, Lakers, and Bulls. If Celtics is selected from the second select box, the third select box should display the names Larry Bird, Bill Russell, and Kevin McHale. I think i have a good start but i can't seem to get the fields to automatically populate with the players. This has to be done solely with JavaScript. Any help would be greatly appreciated? <html> <head> <script type="text/javascript"> <!-- var teams = new Array() teams[1] = new Array() teams[1][0] = "Celtics" teams[1][1] = "Lakers" teams[1][2] = "Bulls" teams[2] = new Array() teams[2][0] = "Yankees" teams[2][1] = "Cardinals" teams[2][2] = "Reds" var basketball = new Array() basketball[0] = new Array() basketball[0][0] = "Larry Bird" basketball[0][1] = "Bill Russell" basketball[0][2] = "Kevin McHale" basketball[1] = new Array() basketball[1][0] = "Wilt Chamberlain" basketball[1][1] = "Jerry West" basketball[1][2] = "Magic Johnson" basketball[2] = new Array() basketball[2][0] = "Micheal Jordan" basketball[2][1] = "Scottie Pippen" basketball[2][2] = "Dennis Rodman" var baseball = new Array() baseball[0] = new Array() baseball[0][0] = "Babe Ruth" baseball[0][1] = "Joe DiMaggio" baseball[0][2] = "Mickey Mantle" baseball[1] = new Array() baseball[1][0] = "Mark McGuire" baseball[1][1] = "Ozzie Smith" baseball[1][2] = "Willie McGee" baseball[2] = new Array() baseball[2][0] = "Pete Rose" baseball[2][1] = "Johnny Bench" baseball[2][2] = "Joe Morgan" function fillTeams() { var whichIndex = document.getElementById("theSport").selectedIndex var numberOfTeams = teams[whichIndex].length for(i=0;i < numberOfTeams; i++){ document.getElementById("theTeams").options[i].text = teams[whichIndex][i] } } function fillPlayers() { var whichIndex = document.getElementById("theTeams").selectedIndex if(document.getElementById("theTeams").selectedIndex=="basketball") var numberOfPlayers = teams[teams[whichIndex]].length for(i=0;i < numberOfPlayers; i++) { document.getElementById("thePlayers").options[i].text = basketball[teams[whichIndex]][i] } else if(document.getElementById("theTeams").selectedIndex =="baseball") for(i=0;i < numberOfPlayers; i++) { document.getElementById("thePlayers").options[i].text = basketball[teams[whichIndex]][i] } } //--> </script> </head> <body> <form> <select id="theSport" onChange="fillTeams()"> <option>Choose a Sport</option> <option>Basketball</option> <option> Baseball </option> </select> <select id="theTeams" onChange="fillPlayers()"> <option>................</option> <option></option> <option></option> </select> <select id="thePlayers" size="3"> <option> ...............</option> <option></option> <option></option> </select> </form> </body> </html> Hi, I'm new to JS and I am trying to build my first script. My problem, is I'm trying to build a multi hide/show script, displaying paragraphs of information. If I want multiple variables for the script do I have to use an array? and if so, how can I construct this array? Here is my script as of now, <!-- // this tells jquery to run the function below once the DOM is read $(document).ready(function() { // choose text for the show/hide link var showText="Resume"; var hideText="Hide"; var profile_showText="Profile"; var profile_hideText="Hide"; // append show/hide links to the element directly preceding the element with a class of "toggle" $(".toggle").prev().append(' (<a href="#" class="toggleLink">'+showText+'</a>)'); $(".profile_toggle").prev().append(' (<a href="#" class="profile_toggleLink">'+profile_showText+'</a>)'); // hide all of the elements with a class of 'toggle' $('.toggle').hide(); $('.profile_toggle').hide(); // capture clicks on the toggle links $('a.toggleLink').click(function() { $('a.profile_toggleLink').click(function() { // change the link depending on whether the element is shown or hidden if ($(this).html()==showText) { $(this).html(hideText); } else { $(this).html(showText); } // profile_toggle if ($(this).html()==profile_showText) { $(this).html(profile_hideText); } else { $(this).html(profile_showText); } // toggle the display $(this).parent().next('.toggle').toggle('fast'); // profile_toggle $(this).parent().next('.profile_toggle').profile_toggle('fast'); // return false so any link destination is not followed return false; }); }); }); //--> Right now the script doesn't work with the bottom two variables profile_"ect." Please help, been working on this for sometime and its probably an easy fix for someone experienced. Thanks! Hi, I am trying to work out a code where I can change the background colour of an HTML page via external JS page. Please note that I will be using different HTML pages with different colours so have to use Arrays. Here is what I have so far!!! here is my function, <script language="JavaScript"> var backColor = new Array(); backColor[0] = '#000000'; backColor[1] = '#111111; backColor[2] = '#222222'; backColor[3] = '#333333'; function changeBG(whichColor){ document.bgColor = backColor[whichColor]; } </script> ------------------------------------- What I need is to apply changeBG function to my HTML page using colour [0] Any help would be greatly appreciated! I was looking at that old Strawberry Fields problem and I thought I'd see about solving it in JavaScript. What I want is an array of chars so that I can set individual elements in the array of arrays. Strings are apparently immutable and can't directly be changed? Here's my code. Code: var field = new Array(); var string0 = "..@@@@@..............." var string1 = "..@@@@@@........@@@..." var string2 = ".....@@@@@......@@@..." var string3 = ".......@@@@@@@@@@@@..." var string4 = ".........@@@@@........" var string5 = ".........@@@@@........" for (var i = 0; i < 6; i++) { field[i] = new Array(); field[i] = eval("string" + i + ".slice('')"); } document.write("field's type is " + typeof field + "<br>"); // object? but it should be explicit array document.write(typeof field[1]) // string? it should explicitly be an array, then it was filled with array elements document.write(typeof field[1][2]); // string - ok, I understand this bit document.write(field[1].length); document.write("<br>"); for (var i = 0; i < field.length; i++) { field[i] = new Array(); for (var k = 0; k < eval("string" + i + ".length"); k++) { field[i][k] = eval("string" + i + ".charAt(" + k + ")"); } document.write("<br>"); } document.write("field's type is " + typeof field + "<br>"); // seriously, an object? document.write(typeof field[1]) // why is this an object instead of an array? document.write(typeof field[1][2]); // string, yeah, I understand this as well document.write(field[1].length); document.write("<br>"); Also, it looks like I can't overwrite a 1-length string that's in the array of arrays. For instance: Code: newField = field; //for loops newField[i][k] = 0; // does nothing, newField's elements remain the same. 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. /* No matter what I do, I have these two scripts, I really want on the same page 1. Is carouselGallery 2. Is flv player <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css"> <!-- body { text-align:center; margin-top: 100px; background-color: #111; } --> </style> <script type="text/javascript" src="js/swfobject.js"></script> <script type="text/javascript"> var flashvars = { imagesXmlPath: "" }; var params = { base: "", salign:"lt", menu:"false" }; var attributes = { }; swfobject.embedSWF("carouselGallery.swf", "myContent", "800", "400", "9.0.0", "expressInstall.swf", flashvars, params, attributes); </script></head> <body> <div id="myContent"> <h1>Alternative content</h1> <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p> </div> </body> </html> Second Is <!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" lang="en" xml:lang="en"> <head> <title>FLV Player FlashVars Example</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <script type="text/javascript" src="swfobject/swfobject.js"></script> </head> <body> <div id="myContent"> <h1>Please Upgrade Your Flash Player</h1> <p><a href="http://www.adobe.com/go/getflashplayer"><img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" /></a></p> </div> <script type="text/javascript"> var flashvars = { flvpFolderLocation: "flvplayer/", flvpVideoSource: "your_video_source", flvpWidth: "640", flvpHeight: "360" }; var params = { menu: "true", allowfullscreen: "true" }; swfobject.embedSWF("FLVplayer.swf", "myContent", "640", "360", "9.0.0", "swfobject/expressInstall.swf", flashvars, params); </script> </body> </html> Can someone please help me figure out how to get both to display on the page? Any help would be GREATLY appreciated. Hi! I'm new with javascript and jQuery in general. So if anyone could help me out it would be greatly appreciated. When the browser is finished loading I want #page2 to be loaded automatically. I can get it to work with: $(document).ready(function () { $('#page2').delay(200); $('#page2').show('slow'); }); But when I click on page2 (when first launched) it wants to load again. It seems like it doesn't understand #page2 is already loaded. I want it to do absolutely nothing when the user clicks on the page2 navigation button. I hope that I explained my problem correctly. Again, I'm a newbie at this and the fact that I got to this point is already a miracle. Thanks in advance! This is my code so far: $(document).ready(function () { $('#page2').delay(200); $('#page2').show('slow'); }); $(function(){ $('#content:not(.nav_block)>dt:not(.active) a,footer .privacy:not(.active) a[rel=privacy]').live('click',function(){ var next=this.rel=='privacy'? $('#privacy'):$(this).parent().next(), width=next.width(), parent=next.parent(), visible=parent.find('>dd:visible').css({overflow:'hidden'}) parent.addClass('nav_block') $('#content>dt,.privacy').removeClass('active') $(this).parent().addClass('active') if(this.rel=='privacy') $('#content>dt>a').removeClass('active').animate({opacity:0}) if(parent.css('left')!=0) next.parent().animate({left:0}) next.show().css({width:'64px'}).stop().animate({width:width+'px'},{ step:visible.length?function(now){ visible.width(width-now) }:'',complete:function(){ next.css({overflow:'visible'}) visible.css({width:width+'px'}).hide() parent.removeClass('nav_block') }}) return false }) <!-- THE PROBLEM SHOULD BE HERE, RIGHT ? --> $('.active a,#content.nav_block').live('click',function(){ return false }) Download the file: http://www.filedropper.com/testfile_1 I'm just learning code. I did a small reaction game project. The idea is that the player is to click on only circles. It works unless a square comes up & is clicked on. My code is he Learning Javascript Here is the actual game: Learning Javascript Any help is appreciated! var n = 123456.789; n.toFixed(0); just starting out JavaScript. So i type the above code in firebug. it returns this result:- "123457" As for as i know, toFixed() converts a number to a string with a specified number of digits after the decimal point. If i have specified 0, which i'm assuming it means 0 digits after the decimal point, why does the 7 appear and the 6 is taken out. really fustrating and can't seem to get my head over it. |