JavaScript - Javascript: Multiple Values From Array
I have the following script that currently returns 4 of the same images. I can't wrap my head around how to get it to return 4 random images (out of the 7 in this example)? Also the links aren't working?
--- Code: var imagenumber = 7 ; var randomnumber = Math.random() ; var rand1 = Math.round( (imagenumber-1) * randomnumber) + 1; images= new Array images[1] = "image1.jpg" images[2] = "image2.jpg" images[3] = "image3.jpg" images[4] = "image4.jpg" images[5] = "image5.jpg" images[6] = "image6.jpg" images[7] = "image7.jpg" var image = images[rand1] links= new Array links[1] = "link1.html" links[2] = "link2.html" links[3] = "link3.html" links[4] = "link4.html" links[5] = "link5.html" links[6] = "link6.html" links[7] = "link7.html" var link = links[rand1] document.write('<div id="image-1"><a href="' + link + '"><img src="' + image + '"></a></div><div id="image-2"><a href="' + link + '"><img src="' + image + '"></a></div><div id="image-3"><a href="' + link + '"><img src="' + image + '" border="0"></a></div><div id="image-4"><a href="' + link + '"><img src="' + image + '"></a></div>') --- Any help would be greatly appreciated! Similar TutorialsHey CF. I'm not great with JS, but I'm trying to build something pretty simple and even that's out of my league. I have a layout with multiple fields that need to be filled randomly from an array on click. I have an array with a bit of jQuery that randomly reloads one field on click, but I need multiple fields filled at once from the same item in the array. Code is below. I grabbed it from a tutorial somewhere, and have made some modifications. Code: <Script> $(document).ready( function() { var foodArray = [ '1', '2', '3', '4', '5' ]; $('.foodtype').loadText( foodArray, 10000 ); // ( array, interval ) }); // custom jquery plugin loadText() $.fn.loadText = function( foodArray, interval ) { return this.each( function() { var obj = $(this); obj.fadeOut( 'slow', function() { obj.empty().html( random_array( foodArray ) ); obj.fadeIn( 'slow' ); }); timeOut = setTimeout( function(){ obj.loadText( foodArray, interval )}, interval ); // reload random text (if not animated) -- entirely optional, can be removed, along with the reload link above (<a href="javascript:;" id="text-reload"><em>randomize</em></a>) $("#text-reload").click( function(){ if( !obj.is(':animated') ) { clearTimeout( timeOut ); obj.loadText( foodArray, interval );} // animation check prevents "too much recursion" error in jQuery }); }); } //public function function random_array( aArray ) { var rand = Math.floor( Math.random() * aArray.length + aArray.length ); var randArray = aArray[ rand - aArray.length ]; return randArray; } </script> That outputs one of the array items into a <span class="foodtype">. What I need is another value next to say "1", eg '1, Blue' and print "Blue" to another span. Can anyone help? The other issue I have is the divs are snap resizing, is there a way set them to animate smoothly? The total height will be variable depending on the combinations that display. Cheers guys, hope someone can help. I want to pass dynamic array values to java script function.how its possible. explain with some code.........
I can't seem to figure out how to accomplish this. In my website, I would like the user to input text into a single or multiple textbox(es) and then have the contents of the textbox(es) stored to either a variable or an array. Then I would like to have that variable/array compared to other arrays. Basically, the user is searching for items in a database. The user can search for as many or as little items as they want. Then the item(s) will be compared to multiple arrays to find out if what the user wants is in the database. So for example, let's say the user is searching for recipes that have all or part of these ingredients: chicken, broccoli, lemon, honey. So, there would have been a total of 4 textboxes...one for each ingredient. These ingredients are stored to an array..lets call it ingredient(). In the database of recipes, each recipe has its own array which includes the ingredients needed to make the recipe, we'll call them tag1(), tag2(), and tag3(). Now, I want the array, ingredient(), to be compared to each of the "tag" arrays to see if any of the "tag" arrays include exactly match the ingredient() tag in part or in whole. Is this possible? Hi all, I have to check for several possible values of a variable and I currently do it like so: Code: (SHIP_TYPE == "M" || SHIP_TYPE == "S" || SHIP_TYPE == "X") But this seems overly manual to me. I'm imagining something like the SQL "IN" function: Code: SHIP_TYPE IN ('M','S','X') Does such a thing exist in JavaScript, or do I need to write my own function? Hello there. I'm having trouble with cookies. I have a bunch of links that when clicked on, create a cookie. For each link I need to be able to save that cookie value to the main cookie name. Here is the click function I'm using to create the cookie: $j('a.createCookie').click(function(e) { var cookieName = "InsightsCookie"; var cookieValue = $j(this).attr("id"); $j.cookie(cookieName, cookieValue, {expires: 365, path: '/'}); }); The end result would be "InsightsCookie: cookieValue, cookieValue, cookieValue" - where each link clicked on would add a value to InsightsCookie. Any help would be much appreciated. Hi, I am setting up an email form & i would like the subject field to hold multiple values, the forrm will be something like this: Name:Mr A Date: 01/01/01 Reason:Football I want the form to send an email without opening an email client & I would like the subject field to look like this: Subject: Mr A, 01/01/01, Football or Subject Mr A - 01/01/01 - Football Can anyone tell me if this is possible, if if is can you please point me in the right direction. Thanks Hi, I'm having problems getting the values of selected checkboxes and outputting them to a textarea. This seems like quite a simple thing to do but its causing me a lot of bother! I am using a mixture of JavaScript and jQuery to find a solution to this. Code: <h2>Booking Form</h2> <form name="booking"> Please choose the days that would suit your visit: <br/> <input type="checkbox" name="days" value="Monday">Monday<br/> <input type="checkbox" name="days" value="Tuesday">Tuesday<br/> <input type="checkbox" name="days" value="Wednesday">Wednesday<br/> <input type="checkbox" name="days" value="Thursday">Thursday<br/> <input type="checkbox" name="days" value="Friday">Friday<br/> </form> <textarea id="output"> </textarea> Code: var values = $("#days").val() || []; $("p#ss").html("<strong>Checked values:</strong> " + values.join(", ")); //This just outputs "Checked values:" to the paragraph 'ss' that I created just to test it this way. Help with this would be appreciated. print "<Font face=\"calibri, Arial\"><table id=\"rnatable\" border=2px width=100%>"; print "<th></th>"; print "<th>a</th>"; print "<th>b</th>"; print "<th>c</th>"; print "<th>d</th>"; print "<th>e</th>"; print "<th>f</th>"; print "<th>g</th>"; while($array = mysql_fetch_array($sql_query)) { $id=$array['a']; print "<tr id=\"newtr\">"; print "<td><input id=\"check\" type=\"checkbox\" name=\"keyword[]\" value=\"$id\" ></td>"; print "<td>".$array['a']."</td>"; print "<td>".$array['b']."</td>"; print "<td>".$array['c']."</td>"; print "<td>".$array['d']."</td>"; print "<td>".$array['e']."</td>"; print "<td>".$array['f']."</td>"; print "<td> <a href=\"http://localhost/rnasearch/retrieve.php?a=$id\">bla</a> </td></tr></font>"; } print "</table>"; } this is part of a php searchengine script that i wrote to retrieve data from a database and as you can see the last column that is g contains a link which when clicked takes the user to the second php script which retrieves additional information of that entry, but this is done for only single entries so as you can see i introduced checkboxes so that the user can check any number of checkboxes and retrieve information as per their wish now to do this i created a <input type=text where i want the value of these checkboxes i.e. $id to be posted in a delimited format so that the user can then click the corresponding button and retrieve the information this is the code <div id="floatMenu"> <ul class="menu1"> <center><li><form name="senddata" method="POST" action="http://localhost/retrieve.php" style="display:inline;"><input id="fasta" type="text" class="multitext"><input name="Fasta" type="Submit" value="Retrieve Fasta"></form> this is a css floating menu....so far so good....everything went fine.... after this i had to write a javascript to do this and i've been stuck there searching forums for the last 4 days! this is the javascript i found from somewhere which came close to doing wht i wanted it to do window.onload = function () { var cb = document.getElementById('check'); var fasta = document.getElementById('fasta'); cb.onclick = function () {fasta.value = cb.value + ","; };}; this script only sends the value of the first checkbox in the table, the others are not found by it, mind you its not the first checkbox selected its the first checkbox that is present in the table how can i resolve this problem so that even if i have n number of checkboxes in my table, if the user chooses to do so they can retrieve n number of information....please help i've almost lost hope in this! hello everybody! this is my first atempt in writing javascript and i have a problem which I have no idea how to solve. I want to take the values from several dropdown forms and make some calculations whit those in order to display a number. Unfortunately the script responts in a way that i cannot identify what is happening. this is a shorten example of my script. Code: <html> <head> <script type="text/javascript"> function calcul() { var pcno = document.plithospc.listplpc.value; var ndno = document.plithosnd.listplnd.value; var hotline = document.hotlform.listhotl.value; var sumhotline = 0; if (hotline == 2) { sumhotline = 8*(1+0.5*pcno) + 2*(1+0.5*ndno); } else if (hotline == 3) { sumhotline = 16*(1+0.5*pcno) + 4*(1+0.5*pcno); } else { sumhotline = 0; } document.write(sumhotline); </script> </head> <body> <FORM NAME="plithospc"> <SELECT NAME="listplpc"> <OPTION SELECTED="SELECTED" VALUE=0>choose one</OPTION> <OPTION VALUE=1>-1-</OPTION> <OPTION VALUE=2>-2-</OPTION> <OPTION VALUE=3>-3-</OPTION> </SELECT> <FORM NAME="plithosnd"> <SELECT NAME="listplnd"> <OPTION SELECTED="SELECTED" VALUE=0>choose one</OPTION> <OPTION VALUE=1>-1-</OPTION> <OPTION VALUE=2>-2-</OPTION> <OPTION VALUE=3>-3-</OPTION> </SELECT> <FORM NAME="hotlform"> <SELECT NAME="listhotl"> <OPTION SELECTED="SELECTED" VALUE=0>choose one</OPTION> <OPTION VALUE=1>1st selection</OPTION> <OPTION VALUE=2>second selection</OPTION> <OPTION VALUE=3>third selection</OPTION> </SELECT> <button type="button" onclick="calcul()">click me</button> </body> does anyone knows how to fix this? thanks in advance 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 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> 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 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> 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, 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 Is there a built in method to remove empty array elements
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> 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 |