JavaScript - Multiple Array Return
What's the most efficient way of me getting all the IDs from the following array (ideally returned in its own array) when the colour = 1? I know I could use a for loop with an if statement in it, but wondered if there was anything better in terms of speed and/or neat code? Thanks in advance.
var directions = [ { id: 1, towards: "Manchester", colour: 1 }, { id: 2, towards: "Sheffield", colour: 1 }, { id: 3, towards: "London", colour: 2 }, { id: 4, towards: "Glasgow", colour: 2 }, { id: 5, towards: "Leeds", colour: 3 }, { id: 6, towards: "Derby", colour: 3 } ]; Reply With Quote 12-19-2014, 11:34 PM #2 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,311 Thanks 82 Thanked 4,754 Times in 4,716 Posts Why not use a filter? Code: var chosen = directions.filter( function(val) { return val.colour == 1; } ); Of course, that does a loop behind the scenes, but it should be faster than a JS for loop. Similar TutorialsIts a ads rotation code: Don know why it doesnt work... Code: <body> <div align="center"> <script> var brw=navigator.appName; var id; if(brw == "Netscape") id=1; if(brw =="Microsoft Internet Explorer") id=2; if(brw == "Opera") id=3; var delay=10000; var k=0; var fcontent=new Array(); var b=new Array(); function go(k) { b[0]='' b[1]='<iframe src="http://........." width="460" height="60" scrolling="no" name="cpm" frameborder="0"></iframe>' b[2]='<iframe width="468" height="60" allowtransparency="false" frameborder="0" hspace="0" vspace="0" marginheight="0" marginwidth="0" scrolling="no" src="http://............"></iframe>' b[3]='<iframe width="468" height="120" allowtransparency="false" frameborder="0" hspace="0" vspace="0" marginheight="0" marginwidth="0" scrolling="no" src="http://............"></iframe>' if(id != 3) b[4]='<iframe width="1" height="1" allowtransparency="false" frameborder="0" hspace="0" vspace="0" marginheight="0" marginwidth="0" scrolling="no" src="http://......."></iframe>' else b[4]='' b[5]='..' ..... ..... b[36]='.... ' return; } begintag='<div style="font: normal 14px Arial; padding: 5px;">'; //set opening tag, such as font declarations fcontent[0]=b[0]+b[1]+b[2]+b[3]+b[4]+b[5]; fcontent[1]=b[6]+b[7]+b[8]+b[9]+b[10]; fcontent[2]=b[11]+b[12]+b[13]+b[14]+b[15]; fcontent[3]=b[16]+b[17]+b[18]+b[19]+b[20]; fcontent[4]=b[21]+b[22]+b[23]+b[24]+b[25]; fcontent[5]=b[26]+b[27]+b[28]+b[29]+b[30]; fcontent[6]=b[31]+b[32]+b[33]+b[34]+b[35]; fcontent[7]=b[0]+b[36]; closetag='</div>'; var ie4=document.all&&!document.getElementById; var DOM2=document.getElementById; var index=0; //function to change content function changecontent(){ if (index>=fcontent.length ) { index=0; ++k;delay=delay+5000; } go(k); if(delay>15000){return;} if (DOM2){ document.getElementById("fscroller").innerHTML=begintag+fcontent[index]+closetag } else if (ie4) { document.all.fscroller.innerHTML=begintag+fcontent[index]+closetag; } ++index; setTimeout("changecontent()", delay); } if (ie4||DOM2) document.write('<div id="fscroller" style="width:700px;"></div>'); if (window.addEventListener) window.addEventListener("load", changecontent, false) else if (window.attachEvent) window.attachEvent("onload", changecontent) else if (document.getElementById) window.onload=changecontent </script> </div> </body> here go(k); function might do this mass (output-->NaN). plz b a help... I need to get this script to work, I only included what im having the problem with. I am Using jQuery Library. Here is how this should work: .btnRoof div is clicked the parent id is retrieved as var pid a function called roof is called which simply changes a css background to "color" the function perform is called to get the "color1[0]" from the array. My Problem: perform() returns the word color1, color10, color1[0], or c. instead of images/cp-roof-blue.png as listed in the array. Code: $(document).ready(function() { var color1=new Array(); color1[0]="images/cp-roof-blue.png"; color1[1]="images/cp-panel-blue.png"; color1[2]="images/cp-trim-blue.png"; function perform(name, x) { alert(name[x]); //alert([name][x]); //alert(name+'['+x+']'); //alert(color1[0]); // correct return name[x]; } function Roof(color) { $("#colorPicker .roof").css("background", "url("+color+")"); } $('.btnRoof').click(function() { var pid = $(this).parent().parent().attr("id"); Roof(perform(pid, 0)); }); }); I tried to clarify as much as possible, please let me know if I need explain further. Thanks. 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? I don't understand the logic of Break, Return False, Return True. It was never really covered in our college class, and I see everyone using it. I got an A in the class, if that 'proves' that I really tried to apply myself. NOTE: I understand what the function is doing. I just don't understand WHEN to use break, return false or return true if the the translator can determine the conditional statements. PHP Code: function submitForm(){ var ageSelected = false; for (var i=0; i<5; ++1){ if (document.forms[0].ageGroup[i].checked == true) { ageSelected = true; break; } } if (ageSelected == false){ window.alert("You must select your age group"); return false; } else return false; } if the the translator can determine the conditional statements, why not write it like this: PHP Code: function submitForm(){ var ageSelected = false; for (var i=0; i<5; ++1){ if (document.forms[0].ageGroup[i].checked == true) { ageSelected = true; break; // what's the point for the 'break'? Won't the rest of the code be ignored since it passed the first condition? } } if (ageSelected == false){ window.alert("You must select your age group"); return false; } // why not leave the last else out? is it just a 'safety' catch, in case something other than true or false is inputted? else return false; // what's the point? } Questions: Why use return true, if the translator knows it's ture? Why use "return false" if the translator knows it's false and the alert window has already gone up? why not use "break" to stop the code? Why use the "return false" at the end "else" statement? Hi room, Hey, I opened up the source code for this page in google chrome and since i'm learning javascript, i wanted see if i could "read" it and figure out what was going on. I'm am having the hardest time understanding "return false" and "return true". Could someone step me through this via interpreting this code (in bold typeface): Code: var DefaultValue = 'Search'; function clearSearch() { if (document.searchForm.q.value == DefaultValue) { document.searchForm.q.value = ''; } } function validateSearchHeader() { if ( document.searchForm.q.value == '' || document.searchForm.q.value.toLocaleLowerCase() == DefaultValue.toLocaleLowerCase() ) { alert('Please enter at least one keyword in the Search box.'); document.searchForm.q.focus(); return false; } return true; } Thanks! I have a web page that opens urls in one seperate window from an array that uses settimeout to slow the loading. Is there coding i can use to replace settimeout that will allow the next url to load after each 1 loads. Here is what i have now. Code: var win = null; var i = 0; var links = [ "http://www.ageofchampions.com/game/gift_accept.php?source=190&sourceu=505119169&wid=53", "http://www.ageofchampions.com/game/gift_accept.php?source=190&sourceu=505119169&wid=57", "http://www.ageofchampions.com/game/gift_accept.php?source=190&sourceu=505119169&wid=194", "http://www.ageofchampions.com/game/gift_accept.php?source=190&sourceu=505119169&wid=196", "http://www.ageofchampions.com/game/gift_accept.php?source=190&sourceu=505119169&wid=242", "http://www.ageofchampions.com/game/gift_accept.php?source=190&sourceu=505119169&wid=286", "http://www.ageofchampions.com/game/gift_accept.php?source=190&sourceu=505119169&wid=335", ]; function aufruf(idx) { if(!win){ win = window.open(); }; win.location.href = (links[idx]); if(idx < (links.length - 1)) { idx++; setTimeout('aufruf(' + idx + ')', 8000); //or setTimeout('aufruf(idx)', 8000); }; }; 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! I'm trying to create two array's on this page: http://www.hollywoodfarmer.com Both array's would be activated by clicking their respective links -- the "I've got more to say" graphic would activate the text array in the bubble. The "Meet my friends" graphic would activate the image array that changes the picture of the celebrities (pls ignore the terrible formatting of the 2nd pic). I'm going to have a relatively large amount of text array variables and probably 5-10 image array variables. Currently, the meet my friends button changes one image, but then it won't change back and is basically broken. The text array is currently activated by refreshing the page and I can't get that button to work at all. Any help would be greatly appreciated. Your forums have gotten me this far! Another homework assignment that I can't quite seem to get to work... I've been asked to do the following using javascript: -Create a function named randInt() with one parameter of "size". Declare a variable named "rNum" equal to a random integer between 1 and the value of the size variable. Return the value of the "rNum" varialbe from the function. -Create a function named getQuote() with one parameter anemd "qNum". The function should create an array named mtQuotes with five quotes; there should be no quote for the array index "0". Return the value of the mtQuotes array for the qNum index. - In the div element of "quotes" insert a script with the following commands: Declare a variable named "randValue" which is euqal to a random integer between 1 and 5 (use the randInt() function). Declare a variable named "quoteText" containing the quote whose array index value is equal to randValue. Write the value of quoteText to the web page. Here is what I have...it returns undefined. thanks. Code: <html> <head> <script type="text/javascript"> function randInt(size) { var rNum=Math.ceil(Math.random()*5); return(rNum); } </script> <script type="text/javascript"> function getQuote(qNum); var mtQuotes = new Array(); mtQuotes[0] = ""; mtQuotes[1] = "I smoke in moderation, only one cigar at a time."; mtQuotes[2] = "Be careful of reading health books, you might die of a misprint."; mtQuotes[3] = "Man is the only animal that blushes or needs to."; mtQuotes[4] = "Clothes make the man. Naked people have little or no influence on society."; mtQuotes[5] = "One of the most striking differences between a cat and a lie is that a cat has only nine lives."; return mtQuotes[qNum]; </script> </head> <body> <div id="quotes"> <script type="text/javascript"> var randValue=randInt(5); var quoteText=getQuote(randValue); document.write(quoteText); </script> </div> Hey 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. hi, Does any one knows the javascript that read step by step single line from form and then store in array , and that array use 4 further references Please help i need this Please Please Please Thanx Regards Fawad Hi, I hope someone can help me. I'll be honest and say I don't know much about javascript, but am fairly comfortable in html. I am building a website that will have multiple image swaps on multiple pages. I am building this in wordpress, and I'm guessing that means my approach will be different than if I wasn't using wordpress. Here's how one page would work: There are 10 images shown. 1,2,3,4,5,6,7,8,9,10. When number 1 is clicked on, I want a new image - 1a. When 2 is clicked on, 2a. So there are 20 different images in all on a given page. Also, I want the user to be able to click on the image again to restore the original image. I would prefer onclick to onmouseover. There will be literally dozens of pages like this on the site, managed by wordpress, so hundreds of images to swap. Basically the first image is a question - the second image is the answer. Is this possible? i have this in my javascript code but have no idea on how a returned value works/where does it return to???? what do i do/or can i do with a value that gets returned??? i am asking this so i can learn on how to use it cos i am new to all this and dont know how it works...please show/explain to me please? thanks here my full code: PHP Code: <?php use_stylesheets_for_form($form) ?> <?php use_javascripts_for_form($form) ?> <html> <head> <script type="text/JavaScript"> function refreshPage(s) { window.location.reload(); if((s.options[s.selectedIndex].value) = "zed-catcher") { var $index = s.selectedIndex; var $value = s.options[$index].value; alert (s.selectedIndex); alert ($value); window.location.reload(); [COLOR="Red"]return &value; //where does it return to ???? how/what to do with a return value???[/COLOR] } } </script> </head> </html> <body> <form action="<?php echo url_for('adminservice/'.($form->getObject()->isNew() ? 'create' : 'update').(!$form->getObject()->isNew() ? '?id='.$form->getObject()->getId() : '')) ?>" method="post" <?php $form->isMultipart() and print 'enctype="multipart/form-data" '?>> <?php if (!$form->getObject()->isNew()): ?> <input type="hidden" name="sf_method" value="put" /> <?php endif; ?> <table > <tfoot> <tr> <td colspan="2"> <?php echo $form->renderHiddenFields(false) ?> <a href="<?php echo url_for('adminservice/index') ?>">Back to list</a> <?php if (!$form->getObject()->isNew()): ?> <?php echo link_to('Delete', 'adminservice/delete?id='.$form->getObject()->getId(), array('method' => 'delete', 'confirm' => 'Are you sure?')) ?> <?php endif; ?> <input type="submit" value="Save" /> </td> </tr> </tfoot> <tbody> <?php echo $form->renderGlobalErrors() ?> <tr> <th><?php echo $form['name']->renderLabel() ?></th> <td> <?php echo $form['name']->renderError() ?> <?php echo $form['name']?> </td> </tr> <tr> <th><?php echo $form['logo_url']->renderLabel() ?></th> <td> <?php echo $form['logo_url']->renderError() ?> <?php echo $form['logo_url'] ?> </td> </tr> <tr> <th><?php echo $form['call_center_number']->renderLabel() ?></th> <td> <?php echo $form['call_center_number']->renderError() ?> <?php echo $form['call_center_number'] ?> </td> </tr> <tr> <th><?php echo $form['catcher_id']->renderLabel(); $catcher_id = $form->getObject()->getCatcherId(); $catcher = LpmCatcherPeer::getByCatcherId($catcher_id); $catcher_name = $catcher->getName(); ?></th> <td> <?php echo $form['catcher_id']->renderError() ?> [COLOR="Red"]<select name="services" onchange="refreshPage(this.form.services)">[/COLOR] <?php $catcher_names = LpmCatcherPeer::getByAllNames(); foreach($catcher_names as $row) { ?> <option value="<?php echo $row->getName()."/".$row->getId();?>" <?php if($row->getName() == $catcher_name) echo ' selected="selected"'; ?> ><?php echo $row->getName();?></option> <?php } [COLOR="Red"]if ($row->getName() == "zed-catcher") //just thought with the return in my java script i can pass the newley selected value back to here and if it meets the if i echo these lines?? { echo $form['service_code']->renderLabel(); echo $form['service_code']->renderError(); echo $form['service_code']; } [/COLOR] ?> </select> </td> </tr> <tr> <th><?php echo $form['price_description']->renderLabel() ?></th> <td> <?php echo $form['price_description']->renderError() ?> <?php echo $form['price_description'] ?> </td> </tr> </tbody> </table> </form> </body> thanks! i'm trying to get some information with this code from my database: Code: function getTableSize(tableName){ db.transaction ( function(tx) { tx.executeSql ('SELECT * FROM '+ tableName,[] , function(tx, r) { return r.rows.length; } ); } ); } but it doesnt work and i cant figure why what i want is that this function return the table size to one variable in another function...something like: Code: var groupTableSize = getTableSize('groups'); I want the output to be this way Student: Doe, John eMail: jd@email.com Course ID: COIN-O70A.01 ----------------------- Can any one pls help me with the display. If I use alert instead of return then I works. But I need to display it in the document. Code: <html> <head> <title>Variable - Examples 1</title> <script type="text/javascript"> function Student(firstName, lastName, email,courseID){ this.firstName = firstName; this.lastName = lastName; this.email = email; this.courseID = courseID; } Student.prototype = { constructor : Student, toString : studentInfo }; function studentInfo(){ return this.firstName + "," + this.lastName + '\n'+ this.email + '\n' + this.courseID; } var student = new Student("Doe", "John", "Doeohn@gmail.com","COIN 70A.01"); </script> </head> <body> <script type="text/javascript"> document.writeln(student.toString()); </script> </body> </html> i achieved to make a chain: Code: function getId(id) { id_elem = document.getElementById(id); return { color:function(e){ id_elem.style.color = e; } }; } so this can be getId("test").color("red"); but what happens if i want to do that? Code: function getId(id) { id_elem = document.getElementById(id); return id_elem; return { ????...... how can i chain if i use return in the first place? I have a javascript that takes information from a form and recompiles that information into a readable shift report. The problem I am having is with returns in the textareas. I tried: Code: theReport = theReport.replace(" ","<br>" but that space puts the rest of the var on a different line and screws with the results. How can I replace a return with <br>? hi, i wanna get the value from javascript to php variable. here is my code, <html> <body> <select name="drop" size="10" onchange="drp_selectd_value(this)"> <option>One</option> <option>Two</option> <option>Three</option> <option>Four</option> <option>Five</option> </select> <?php echo "The PHP value".'<script>value_return();</script>'; $p='<script>y;</script>'; ?> </body> </html? <script> var x; var y=100; function drp_selectd_value(sdf) { x=sdf.value; alert("Value is : " +x); value_return(x); } function value_return(val) { alert("Second Function calling : "+val ); return val; } </script> This code does not working!!! How can i fix tis problem???I m expecting for the reply.. Thanks in advance hi,i don't understand about the jquery basic example the code is below PHP Code: <html> <head> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("button").click(function(){ $('p').addClass(function(n){ return 'par_' + n; }); }); }); </script> <style type="text/css"> .par_0 { color:blue; } .par_1 { color:red; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> <p>This is another paragraph.</p> <button>Add classes to p elements</button> </body> </html> i want to understand about the how is work function(n){ in the function a and how work return function return 'par_' + n; thanks mate |