JavaScript - Assign Values From Array
I'm having problems with selecting values from array.
I have a dropdown box where you choose what fruit you want to buy. When selected the array should assign 2 values to that fruit. I don't know how to do that. Here's what I have.. I added comments. Javascript part: Code: <script type="text/javascript"> function Fruits() { var selectfruit = newArray( //assigning values to fruit selected from dropdown box newArray("Banana", 1, 1), newArray("Apple", 1.2, 0.5), newArray("Mango", 1.1, 0.9), newArray("Orange", 0.1, 9.99)); var howmanyfruits = Number(document.getElementById("howmanyfruits").value); // how many fruits are you buying var totalfruitsowned = Number(document.getElementById("totalfruitowned").value); // How many fruits do you already have /* cash and coupons needed to buy fruits. cash is cpst for 1 fruit. coupons is cost for 1 fruit cash_all is cost for all fruits you're buying coupons_all is cost for all fruits you're buying each fruits requires cash AND coupons to be bought. Cash and coupons are tied to the first values in Array. Eg. If you choose Apple that value would be 1.2 The 'fruitsmaxtobuy' variable is not tied to the first value, but the second one in array. If you choose Apple that value would be 0.5. */ var cash = Math.round(((totalfruitsowned * 0.51 * selectfruit) + 700)*10)/10; var coupons = Math.round(((totalfruitsowned * 0.51 * selectfruit) + 850)*10)/10; var cash_all = Math.round((howmanyfruits * cash)*10)/10; var coupons_all = Math.round((howmanyfruits * coupons)*10)/10; var fruitsmaxtobuy = Math.round((totalfruitsowned * 0.12 * selectfruit)*10)/10; /* Display Error if nothing is entered or if you forget to enter total fruits */ if (((howmanyfruits=="" || howmanyfruits==null) && (totalfruitsowned=="" || totalfruitsowned==null)) || ((howmanyfruits==Number(document.getElementById("howmanyfruits").value)) && (totalfruitsowned=="" || totalfruitsowned==null))) {document.getElementById("cash").innerHTML = "Error"; document.getElementById("coupons").innerHTML = "Error"; document.getElementById("cash_all").innerHTML = "Error"; document.getElementById("coupons_all").innerHTML = "Error"; document.getElementById("fruitsmaxtobuy").innerHTML ="Error"} else { document.getElementById("cash").innerHTML = cash; document.getElementById("coupons").innerHTML = coupons; document.getElementById("cash_all").innerHTML = cash_all; document.getElementById("coupons_all").innerHTML = coupons_all; document.getElementById("fruitsmaxtobuy").innerHTML =fruitsmaxtobuy} } </script> HTML part: Code: <form action="" id="fruitcost"> <table align="center" width="37.5%" cellpadding="0" cellspacing="0"> <tbody> <tr> <th colspan="2" align="center">Fruit cost calcultor</th> </tr> <tr> <td>Select Fruit:</td> <td align="center"><select id="selectfruit"> <option>Banana</option> <option selected>Apple</option> <option>Mango</option> <option>Orange</option> </select> </td> </tr> <tr> <td>Total Fruits Owned:</td> <td align="center"><input id="totalfruitsowned" type="text" /></td> </tr> <tr> <td>How many fruits are you buying:</td> <td align="center"><input id="howmanyfruits" type="text" /></td> </tr> <tr> <td>Money Needed to buy 1 fruit:</td><td><font id="cash"></font></td> </tr> <tr> <td>Coupons Needed to buy 1 fruit:</td><td><font id="coupons"></font></td> </tr> <tr> <td>Money Needed:</td><td><font id="cash_all"></font></td> </tr> <tr> <td>Coupons Needed:</td><td><font id="coupons_all"></font></td> </tr> <tr> <td>Nr. of fruits you can buy:</td><td><font id="fruitsmaxtobuy"></font></td> </tr> <tr> <td align="center" colspan="2"><input type="button" value="Submit" onclick="Fruits()" /></td> </tr> </tbody> </table> </form> Similar Tutorialshi guys i hava gridview gvcustomers with following fields latitude,longitude,customer and i have a javascript function in my aspx page fucntion Customer() { AddCustomer(lat1,long1)--- row1 of gridview lat long AddCustomer(lat2,long2)--row2 of gridview lat long } in the above function i would like to loop through the gridview and get the latitude and longitude colmns in the function instead of hardcoding as i have been doing now...thank you i advance EDIT: goto post #7 here goes JS code: (keep an eye on codes of type: document.getElementById('footerX').innerHTML=X Code: function details() { var choo = document.getElementById("choo"); aa = choo.chooserver.value; bb = choo.chooversion.value; if(aa==1) {k=0} else if(aa==2) {k=1} else {k=false} pa= domain[k].getElementsByTagName("server") ; pb=""; pc = domain[k].getElementsByTagName("version"); pd= domain[k].getElementsByTagName("date"); pe= domain[k].getElementsByTagName("month"); pf= domain[k].getElementsByTagName("year"); ta = (bb==1)? " T4 ":(bb==2)? " T3.6 " :(bb==3)? " T2.5 " : 100 ; versions(ta); document.getElementById('footer1').innerHTML='one'; } function versions() { for (i=0;i<=pc.length;i++) { a = pc[i].childNodes[0].nodeValue; b = pa[i].childNodes[0].nodeValue; comparedate(d,g,f); dates(i, a); document.getElementById('footer2').innerHTML='two'; if (a==ta) { addto() document.getElementById("mc"+i).innerHTML= txt ; document.getElementById("md"+i).innerHTML= txt2 ; } document.getElementById('footer3').innerHTML='tee'; } document.getElementById('footer4').innerHTML='fou'; } HTML: Code: <div id = "conten2"> <table id="tb1" border="1px"> </table> </div> <div id = "footer"> feet </div> <div id = "footer1"> feet1 </div> <div id = "footer2"> feet2 </div> <div id = "footer3"> feet3 </div> <div id = "footer4"> feet4 </div> <div id = "footer5"> feet5 </div> Desired Output: feet one two tee fou feet5 Output: feet feet1 two tee feet4 feet5 Area of error predicted: inside the for loop, the statement immediately after loop is not executed once loop ends, nor does it return to original function for execution of other statements which were written after the function containing the loop was called.... I have to update the rowid(assigned to checkbox) whenever the textbox value is updated and this needs updating value of document.getElementsByName('rf_select[]') when checkbox value matches the textbox id. There can be mutliple number of rows each with a uniqueID (checkbox value) that matches with the textboxID onload. Code :- <td align="center"><input type='checkbox' name='rf_select[]' id='rf_select' value="rowId" CHECKED border="none"/> <td align="left"><input type='text' name='policy_no' id="rowId" size='25' value="test" onBlur=handleRowId('policy_no'); /></td> <script language="javascript"> function handleRowId(){ var arr = new Array(); var rowarr = new Array(); arr = document.getElementsByName('policy_no'); rowarr = document.getElementsByName('rf_select[]'); for(var i = 0; i < arr.length; i++) { var obj = arr.item(i); //alert(obj.id + " = " + obj.value); for(var j=0; j< rowarr.length; j++){ if(rowarr[j].value == obj.id){ document.getElementsByName('rf_select')[j].value = rowarr[j].value+"#@#"+obj.value; } } } } </script> I am having problem assigning values here - document.getElementsByName('rf_select')[j].value = rowarr[j].value+"#@#"+obj.value; Any help is appreciated. Hello, I'm Stephen Martin, an undergraduate Psychology student and researcher. Although I am a self-proclaimed tech geek, the extent of my knowledge ends abruptly at any sort of coding. I need help from anyone who is willing. The paradigm: I am currently investigating the decision making strategies in a particular population (I cannot reveal too much, lest our study be scooped by competing researchers in the field). The paradigm that we use is built through a package called MouseLabWeb (http://www.mouselabweb.org/). MLWeb basically provides an interface for researchers to create a html/php/js/css website that presents a grid (table). A small example is shown on the aforementioned website. The javascript functions allow each participant's events to be recorded, timestamped, and written to a MySQL database. This allows the researcher to know which cells the participant viewed, in what order, for how long, and ultimately to which decision the participant came. Additionally, the PHP/HTML creates the table, but the data within it is populated by the javascript. This is a blessing and a curse. Here is why. The problem: The javascript offered by MLWeb allows the cells to be randomized. This is necessary, because in such paradigms, counter-balancing is required, otherwise there would be order effects (e.g., people tend to automatically read from the upper left) that are not controlled for. So the order of the columns and rows are randomized, the data which is then placed into the html/php table. For the current study, we want the cells corresponding to particular types of information to be shaded differently. For example, we'd want cells that contain bad information to be dark, cells that contain neutral info to be grey, and cells that contain good information to be white. The problem is that setting these values (style="background-color: #XXXXX) only applies to the table as created by the PHP. It only affects the position, and does not consider the information that it is filled with. We want the information that a cell is filled with to dictate what background-color the cell is. Example of the problem (A,B,C are the different types of info, with the surrounding character implying shading) What we want: Unrandomized: [.A.] [|B|] [#C#] Randomized: [#C#] [.A.] [|B|] What the problem is: Randomized: [.C.] [|A|] [#B#] Again, thank you for reading this long post. I'm up for any suggestions! TL;DR The website uses PHP to render a table and javascript to populate it. Javascript randomizes the column and row order upon each visitation, thus randomizing the cells. How do I make javascript issue a background-color change to each cell according to the information that it is populated with. Hi! I am quite new to the world of JavaScript as I have done basic corse for it... and I have learnt that best way to understand it is to play around with it... but now I am stuck with on of the problem!! Problem: How can we assign text box input values by user to a variable and display that variable back on another element of the same HTML document(dynamically)... Conditions: The value has to be stored as a JavaScript variable only. No server-side script is to be used and has to be done locally. Please help! If I assign an array to another variable, any changes to the array change both variables. Is it a pointer instead of a copy? Try this: Code: <script type="text/javascript"> Arr=['a','b','c']; Arr2=Arr; Arr[1]='_'; alert('Array 1: '+Arr); alert('Array 2: '+Arr2); // Both arrays become 'a','_','c' </script> Why's this happen? Is it to be expected? Variables don't do this but it's happening for arrays in IE and FireFox, maybe all others. Hey. I have a string and I can return say, the fourth letter with output[3], but i can't assign a value to it for some reason: I am trying to make hang man Code: <!DOCTYPE html> <html> <head> <script src="jquery.min.js"></script> <script> $(document).ready(function(){ var word, output, wordLength, stringLength, newLetter, letters; var i, n, k, health, wcheck; word = "word"; output = ""; letters = ""; wordLength = word.length; for(i = 0; i < wordLength; i++){ output += "_"; } $("#inputLetters").keyup(function(){ newLetter = $("#inputLetters").val(); $("#inputLetters").val(""); letters += newLetter; wcheck = false; for(i = 0; i < wordLength; i++){ if(word[i] == newLetter){ wcheck = true; output[i] = newLetter; } } if(wcheck = false){ health++; } $("#letters").html(output + "<br />" + letters); }); }); </script> </head> <body> <span id="letters"> </span> <br /> <br /> <input id="inputLetters" type="text" /> </body> </html> Hi, I was working on this problem that asks me to return an array of scores for each string (only for its content part, not URL) in the global variable, which is an array. For example, alert a score of 0 if the string z is not found, 1 if found once, and 2 for twice. My problem is that I can get the code to alert if it has found the word (ex. "the"), but I cannot manage to : a) Assign separate scores for each string. b) Make the search case insensitive i.e. "the" will appear in 0,1, but not in 2, where it is capitalized I would appreciate any help! [CODE] var c = ["[www.facebook.com] Facebook is the best social networking site to coccent with your friends. ", "[www.google.co.uk] Google is the worldwide search engine. ", "[www.bbc.co.uk] The best news source for starting your day. "]; function findScore(z) { for (var i=0; i<c.length; i++) { var a = c[i].toString(); var b = a.search(z); if(b>-1) { alert (z + " found in array " + i); } } } findScore("the"); [CODE] Sorry for not being able to wrap the code! hello I am having a problem to add numbers store in an array. arrayValues[0][0] = 1; arrayValues[0][1] = 2; var col = 0; var sum; for ( var row = 0; row < index; i++ ) sum += arrayValues[col][row]; my result is ==> 12 it is defining my sum variable as string. even I try do do this var sum = 0; to define sum as numeric variable. my result was ==>012. Any idea, this is my first javaScritp code. Thanks. Hi Guys, How do I sum the values of an array and output the result using document.write? Say my array is var number=new Array(1.234,56.43,1.02); THANKS Thought this wud work? Code: <script type="text/javascript"> var x = [1, 2, 3, 4, 5, 6, 7, 8, 9]; document.write(sum(x)); </script> hi, I have this keypressed function: Code: function keyPressed(event, input) { if (event.keyCode == 8) { return true; } var char = event.which ? event.which : event.keyCode; char = String.fromCharCode(char); var exers = "1234 1234 1234"; return (exers.charAt(input.value.length) == char); } This function allow me to press in order the numbers in array (index0). It is works very well. But i want to add an array with more exercises like: Code: var exerc = new Array(); exerc[0]= "1234 1234 1234"; exerc[1] = "5678 5678 5678"; exerc[2] = "9012 9012 9012"; Also, i have a dropdown menu that parser options from a xml file: Code: <form> <select style="width:100px" id='courses'> </select> </form> and my xml file looks like: Code: <courses> <course title="exercise 1"> <lesson>1234 1234 1234</lesson> </course> <course title="exercise 2"> <lesson>5678 5678 5678</lesson> </course> <course title="exercise 3"> <lesson>9012 9012 9012</lesson> </course> . . . </courses> *I write the same index because i have two input field. I see the first choose (depend on dropdown) in first input, and i rewrite the same exercise in the second input. So, it's something like an exercise for me and i stack here. - I repeat. It is work with only one index very well. The problem is that, when i add more that one index in the array. Any suggestion about my problem?Javascript it is not my strong point I try this but it is doesn't work.Baybe it is totally wrong! Code: function keyPressed(event, input) { if (event.keyCode == 8) { return true; } var char = event.which ? event.which : event.keyCode; char = String.fromCharCode(char); var exerc = new Array(); exerc[0]= "1234 1234 1234"; exerc[1] = "5678 5678 5678"; exerc[2] = "9012 9012 9012"; for (i=0;i<exerc.length;i++) { document.getElementById("courses").selectedIndex; } return (exers.charAt(input.value.length) == char); } Hi How can i output two maximum numbers of an array if they are equal? var flower["roses", "violets", "buttercups", "daisies"]; var flowerAmounts[9, 8, 3, 9]; Output should be: The maximum amount of flowers is 9. There are 9 roses and 9 daisies. Hope someone can help, thanks 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> Hello guys, I'm very new to javascript and I have a question. I'm creating a calculator. This calculator has a memory function in it. When people inserted a value in the calculator then the user can save this value with button "M+". When the user wants to use this value again he can simply paste it into the calculator with button "MR". This works fine, however I'm working on a function that will remember the different memory value when a user clicks on the button. So if the memorized value is 5, and the user will click the button "ATA" (add to array) it will create the value "5" into an array (which will be the value of array[0]. When the user remembers a other memory value, lets say 9, and clicks on the button "ATA" again it will create the value "9" into the same array (which will be the value of array[1]). My current method doesn't seem to work, it only saves the first value. What am I doing wrong here? Code: // ATA function saveAta() { var saved = new Array(); saved.push(m); // variable m is from the function of M+ } Got the complte script running he http://xquzive.com/javascript/calc.html Is there a built in method to remove empty array elements
Hi, I'm trying to find out the min and max values of randomly generated values in a array list. Its a checkout system that randomly add a customer to a queue and does the same to remove a customer depending on a randomly generated number. Ive managed to figure out the mean of the queue but can only display the total values added to the list rather than display when the queue was at it biggest value. If anyone can point me in the right direction it would be greatly appreciated. ___________________________________________________________________ import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.ListIterator; import java.util.Queue; import java.util.Random; public class Checkout { private Queue<String> tillQueue; private int rndNumber; private int currentLen; private ArrayList <Integer>lengthList; private Random r; public Checkout() { tillQueue = new LinkedList<String>(); currentLen = 0; //current queue length lengthList = new ArrayList <Integer>(); r= new Random(); } public void simulation() { System.out.println("Time" + "\t" + "Rnd" + "\t" +"Queue Status"); for (int t=2; t<10; t++) { rndNumber =r.nextInt(6)+1; if (rndNumber==2 || rndNumber==4 || rndNumber==6) { tillQueue.add(String.valueOf(t)); currentLen++; } else if ((rndNumber==1 || rndNumber==3) && !tillQueue.isEmpty()) { tillQueue.remove(); currentLen--; } else if(rndNumber==5) { //do nothing } if(tillQueue.isEmpty()) { System.out.println(t + "\t" + rndNumber + "\t" + "Queue is empty"); } else { System.out.println(t + "\t" + rndNumber + "\t" + tillQueue.toString()); } lengthList.add(new Integer(currentLen)); } } public double CalculateMeanLength() { double mean=0.0; int sumOfLengths = 0; for (int i = 0; i<lengthList.size();i++) { sumOfLengths=sumOfLengths+(Integer)lengthList.get(i).intValue(); } mean = (double)sumOfLengths/lengthList.size(); return mean; } public int ShowMax() { int max = 0; //i know its going to be a for loop of some kind but not sure how to do it// } ----------------------------output via controller================ Time Rnd Queue Status 2 6 [2] 3 5 [2] 4 3 Queue is empty 5 5 Queue is empty 6 1 Queue is empty 7 5 Queue is empty 8 5 Queue is empty 9 4 [9] mean length = 0.375 max length = 3 //the max length here should be 1 =========================================== Thanks in advance for your help Hello, I have an array containing 100 different values. How would I randomly pick 25 of them for display? For now I do: PHP Code: for (var i=0; i<markers.length && i<25; i++) { html += markers[i].name + '<br />'; } Which of course returns 25 values but always in the same order which is not what I want. Thanks in advance! PS. My array could also contain only 20 values, in which case I would like the function to display the 20 values randomly sorted. Hi all, Decided to start learning JavaScript, started 2 days ago. Anyway, I'm trying to create a simple script spits out a styled result based on a user input. Here is my JS: Code: function dispTable (form) { var userCost2 = form.venCost2.value * 1; marArray = new Array ("0.05", "0.1", ".15", "0.2", "0.25", "0.3", "0.35", "0.4", "0.45", "0.5", "0.55", "0.6", "0.65", "0.7", "0.75", "0.8"); for (var i=0; i<marArray.length; i++) { document.tableDiv.innerHTML = "<div>" document.tableDiv.innerHTML = userCost2; document.tableDiv.innerHTML = marArray[i]; document.tableDiv.innerHTML = + userCost2 * marArray[i]; document.tableDiv.innerHTML = "<\/div>"; } } Here is my HTML: Code: <div class="container"> <form name="lasoCalcTable"> <span>Enter Vendor Cost</span> <input class="textForm" name="venCost2" id="venCost2" type="text" size="8" /> <hr /> <input class="butForm" name="calcTblBut" type="button" value="Calculate" onclick="dispTable()" /><br /> </form> <div title="tableDiv" id="tableDiv"> </div> </div> The problem is that nothing is happening when I press the calculation button. What I would like to happen is to display a div element for each value in the array which displays the entered value from VenCost2, the current Margin %, and the result of VenCost2 * margin%. I want this to display on the same page and underneath the calculation button, preferably not having to reload the page. I thought this was going to be relatively easy but doesn't seem so! Thanks for your help hi, i am currently working on aptana stuidio Nokia WRT to create a mobile widget. the projects requires the retrieval of data from a database. I've created a java servlet in eclipse to connect and execute query to the database. In aptana, i'm using js file and html file. i am able to connect to the servlet, process the data (split it) and store in an array to display the retrieved data on screen. But now i am facing problems to put the retrieved data (array) into a drop down list for selection. can i do it in a js file? thanks =) I am a beginner. I am trying to create a script to randomly assign recipients to givers for a Secret Santa. The participants are placed into groups. A giver cannot be assigned a recipient with whom he is grouped. I want to return all of the assignments in a table. I have made the following script. When I run it, it seems to get stuck in a loop. Any ideas why this might be? If you have any questions about how I want this thing to run, feel free to ask. Your help would be greatly appreciated. Code: <html> <head> <script type="text/javascript"> var giver = new Array(); giver[0] = new Array("CL","BL"); giver[1] = new Array("LP","JP","BP"); giver[2] = new Array("JO","MO"); giver[3] = new Array("JC","TC"); var recipient = new Array(); recipient[0] = new Array("none","none"); recipient[1] = new Array("none","none","none"); recipient[2] = new Array("none","none"); recipient[3] = new Array("none","none"); var string = "<table><tr><td>Giver</td><td>Recipient</td></tr>"; function chooseRecipient() { var x; for (x in giver) { var y; for (y in giver[x]) { var a = Math.floor(Math.random() * giver.length); while (recipient[a].indexOf("none") < 0 || a == x) { a = Math.floor(Math.random() * giver.length); } var b = Math.floor(Math.random() * giver[a].length); while (recipient[a][b] != "none") { b = Math.floor(Math.random() * giver[a].length); } recipient[x][y] = giver[a][b]; string += "<tr><td>" + giver[x][y] + "</td><td>" + recipient[x][y] + "</td></tr>"; } } string += "</table>"; document.write(string); } </script> </head> <body onload="chooseRecipient()"> </body> </html> |