JavaScript - Adding Integers In An Array
Okay so im just doing a little test and this might seem like a really stupid question but i cant figure it out...all i simply want to do is take all those numbers and get the sum then display the sum in a document.write
in theory i should get 10 but i dont and idk why i have tried many many things Code: var numbers = new Array(); numbers[0] = 1; numbers[1] = 2; numbers[2] = 3; numbers[3] = 4; thanks Similar TutorialsHi all, I have an array holding 100 randomly generated integers between 0-9 inclusive...firstArray[99] how do i use a second array to keep count of how many times each integer is generated..secondArray[9] Hi all, I have an array containing numbers. I want to order this numbers contained from major to minor in order to print them .. Here's what I have done: Code: var arr = new Array(6); arr[0] = "10"; arr[1] = "5"; arr[2] = "40"; arr[3] = "25"; arr[4] = "1000"; arr[5] = "1"; function sortNumber(a,b) { return b - a; } for(var i=0;i < 6; i++){ var myarray = arr[i]; myarray.sort(sortNumber); alert(myarray); } But I get no alert and a "myarray.sort is not a function" error. What am I doing wrong? How can I solve this? Thanks a lot in advance! I want to make a script that will insert all text type inputs into an array. From there I want to be able to call them and edit them. Here is what I have so far and it is not working. var phone1 = '702' var inputArray = new Array(); var inputs = document.getElementsByTagName('input'); inputs; if (input.type == 'text') { inputArray.push(inputs.id); } inputArray.reverse(); inputArray[0].value = phone1; I know you can add data to array wiht the push() method but can you add a whole new line as in a = new Array a [1] [1,2,3] so it would create a new line a [2] [4,5,6]; The syntax to the array i think is wrong but you get the question. Resolution: Code: <script type="text/javascript"> function amountTotal() { var totalDonations = 0; for (var i = 0; i < amount.length; i++) { totalDonations += amount[i]; } document.write(totalDonations); } </script> I have an array in a seperate.js file that I need to step through a FOR loop to grab all these values and add them together. Here is a small sample of the array's: Code: city = new Array(); state= new Array(); zip = new Array(); amount = new Array(); date = new Array() firstName[0]="Nina"; lastName[0]="Largent"; street[0]="88 Regal Lane"; city[0]="Williamsburg"; state[0]="KY"; zip[0]="40769"; amount[0]=125; date[0]="2011-09-18"; firstName[1]="Mike"; lastName[1]="Hart"; street[1]="Da404 Barrow Street"; city[1]="London"; state[1]="KY"; zip[1]="40744"; amount[1]=75; date[1]="2011-09-18"; Here is the loop step through that I have: Code: <script src="arrays.js" type="text/javascript"></script> <script type ="text/javascript"> function amountTotal() var totalDonations = 0 for (var i=0; i < amount.length; i++) { } </script> I am stuck on how to grab each amount index and add them together to save them as the amountTotal variable. I've got this little chunk of code running on my freelance portfolio site - on each page (different sections of my portfolio) I have 6 thumbnails and a full sized graphic with some descriptive info, you click the thumbnail and it switches the graphic and other info, that all works fine. But on one page I have some web stuff and I'd like to make the var 'clientinfo' into a link to go to the client's website. I know I need to add an array with the website links, but then I'm not sure how to implement it into the html, I've tried various things I've found on here but I'm not getting anywhere on my own. I know it's something pretty simple (for someone who knows what they're doing) but I just can't seem to grasp it. Can anyone help? the js is like this: $(function() { $(".image").click(function() { var image = $(this).attr("rel"); var title = $(this).attr("title"); var description = $(this).attr("content"); var clientinfo = $(this).attr("clientinfo"); $('#gallery').hide(); $('#gallery').fadeIn('slow'); $('#image').html('<img src="' + image + '"/>'); $('#title').html(title); $('#description').html(description); $('#client').html(clientinfo); return false; }); and then the HTML anchors are like this: <a href="#" rel="images/gallery/web/site1.png" title="Site One" content="This is the descriptive info for site number one" clientinfo="Site One link" class="image"><img src="images/gallery/web/t_site1thumb.png" class="thumb" border="0"/></a> Years ago I created HTML that employs checkboxes and textboxes. I am now writing JS with the intention of adding flexibility and limiting redundancy. I am not sure I truly understand how to correctly interact the two though. For example, one of my scripts have arrays that contain the names of the checkboxes and textboxes, with a 'for' loop to document.write() them to references within the HTML code. This does not seem to be working for me though. Here is what I have thus far (in short): Code: <script language="javascript"> var teamNames = new Array(3); teamNames[0]="South Africa"; teamNames[1]="Mexico"; teamNames[2]="Uruguay"; for (i=0; i<=31; i++) { document.write("<p>" + teamNames[i] + "<\/p>"); } </script> </head> <body> <tr><td>Jun 11</td><td><input type="checkbox" name="teamNames[0]" value="teamAbbr[0]"></td> </body> I've left out a lot of the code (to include the teamAbbr array, but you get the points. I've tried moving the JS within the HTML body and playing with the reference syntax, but nothing so far. Any help would be great! Hi all, I have a div element (i.e. <div id="main">) that contains a number of links, each with white background colors and its top and left style properties set to different values. I need to do several things with the anchors when they are clicked: When a white anchor is clicked, its background color is turned yellow and its coordinates (top and left style property values) are added to an array. The coordinates for a single anchor is to be separated by a hyphen; coordinates for multiple anchors are to be separated by a comma (eg. "0-9,0-18") When a yellow anchor is clicked, its background color is turned white and its coordinates are removed from the array. The values in the array are to be the value for a hidden input element, all separated by commas. I'm a Javascript novice and don't know where to begin. Can someone help me with this? Thanks in advance, Dude-Dastic Write a program named Median.java that asks the user for three integers and outputs the median. I have to do this using if else statements. It seems really easy, but I can't figure it out. Help! Here's my code: Code: import java.util.*; public class Median { public static void main(String[] args) { Scanner console = new Scanner(System.in); System.out.println("Please enter number 1"); int max = console.nextInt(); int min = max; int median = min; for (int i=2; i <= 3; i++) { System.out.println("Please enter number "+i); int enteredNumber = console.nextInt(); if (enteredNumber > max) { max = enteredNumber; } else { enteredNumber = median; } if (enteredNumber < min) { min = enteredNumber; } else { enteredNumber = median; } } System.out.println("The median is: "+median); } } When I run this it just gives me back the first number I entered. I am working on a page where the user will select a location from a dynamically generated dropdown list. I was able to create the php multidimensional array (tested and working) from a MySql database using the users information at login, but I'm having problems converting it to a javascript multidimensional array. I need to be able to access variables that I can pass to a number of text fields within an html form. For instance, if a user belongs to a company with multiple addresses, I need to be able to let them select the address they need to prepopulate specific text fields. php array creation: Code: if ($row_locations) { while ($row_locations = mysql_fetch_assoc($locations)) { $mail[$row_locations['comp_id']]=array('mailto'=>$row_locations['mailto'], 'madd'=>$row_locations['madd'], 'madd2'=>$row_locations['madd2'], 'mcity'=>$row_locations['mcity'], 'mstate'=>$row_locations['mstate'], 'mzip'=>$row_locations['mzip'], 'billto'=>$row_locations['billto'], 'badd'=>$row_locations['badd'], 'badd2'=>$row_locations['badd2'], 'bcity'=>$row_locations['bcity'], 'bstate'=>$row_locations['bstate'], 'bzip'=>$row_locations['bzip']); } } javascript function - this should create the array and send variables to text fields. Code: function updateAddress() { var mail = $.parseJSON(<?php print json_encode(json_encode($mail)); ?>); { if (comp_id in mail) { document.getElementById('mailto').value=mail.comp_id.mailto.value; document.getElementById('madd').value=mail.comp_id.madd.value; document.getElementById('madd2').value=mail.comp_id.madd2.value; document.getElementById('mcity').value=mail.comp_id.mcity.value; document.getElementById('mstate').value=mail.comp_id.mstate.value; document.getElementById('mzip').value=mail.comp_id.mzip.value; } else { document.getElementById('mailto').value=''; document.getElementById('madd').value=''; document.getElementById('madd2').value=''; document.getElementById('mcity').value=''; document.getElementById('mstate').value=''; document.getElementById('mzip').value=''; } } } Where is this breaking? Thanks in advance. I have the following array that contain the people who are on off on certain time: Code: var all = [ ["1234", "Jim", "2011-10-23 00:00:00", "2011-10-25 07:00:00"], ["1235", "Jack", "2011-10-21 00:00:00", "2011-10-21 08:00:00"], ["1236", "Jane", "2011-10-11 00:00:00", "2011-10-11 00:30:00"], ["1237", "June", "2011-10-20 00:00:00", "2011-10-20 12:00:00"], ["1238", "Jill", "2011-10-14 00:00:00", "2011-10-14 11:00:00"], ["1239", "John", "2011-10-16 00:00:00", "2011-10-16 10:30:00"], ["1240", "Jacab", "2011-10-19 00:00:00", "2011-10-20 08:30:00"] ]; The above array, I wish to use javascript to insert into the FullCalendar (http://arshaw.com/fullcalendar/). I notice that the only way seems to be using the FullCalendar array style (or structure) as follows: Code: $('#calendar').fullCalendar({ events: [ { title : 'event1', start : '2010-01-01' }, { title : 'event2', start : '2010-01-05', end : '2010-01-07' }, { title : 'event3', start : '2010-01-09 12:30:00', allDay : false // will make the time show } ] }); So, the question is: How do I insert my array to match with the FullCalendar array? cause FullCalendar array had a different array structure from my array - and I don't think so that I can write in this way: Code: $('#calendar').fullCalendar({ events:all }); Appreciate any help provided. 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? Hey guys, I'm hoping this is possible or that there is an easier way to do this. I'm having an issue with displaying data from one array that contains information about users in a table that is controlled by a different array. Is it possible to do this or is this use of arrays to display the data the wrong approach? The table is located on one webpage, I simply want to extract one piece of information that I have placed in the initial array as part of the login script that contains user information (for validation for login etc) and display it in a table on the new webpage that is opened as a result of successful validation of the user details. I'm completely stumped and after many attempts I just can't seem to get it to work. Hi, In a nutshell,can anyone tell me how to copy a 2d (two dimensional ,2 dimensional) php array to 2d javascript array?I would be obliged if anyone can provide me a method of doing that OR I have written a code to copy a 2d php array to a 2d javascript array.It is working but there is one problem(please see the following).Can anyone tell me what I am doing wrong here? The 2d php array is $quest[100][6] and the 2d javascript array is questions[100][6] . I have written the javascript code inside the <?php....?> itself using echo "<script language="javascript" type="text/javascript">.......</script>; Now ,inside the javascript,when I try to copy the 2d php array to the 2d javascript array using the following method it works questions[0]= ["<?php echo join("\", \"", $quest[0]); ?>"]; questions[1]= ["<?php echo join("\", \"", $quest[1]); ?>"]; ... and so on However, if I try to do the same using the following method it does not work for (var i= 0; i <= 99; i++) { questions[i]= ["<?php echo join("\", \"", $quest[i]); ?>"]; } Why is that?What mistake am I making?Any help will be deeply appreciated.Thanks -----------------------------THE CODE------------------------------------ <?php Access database and store result of mysq_query in $result....... $result = mysql_query($query); for ( $count = 0; $count <= 99; $count++) { $quest[$count]=mysql_fetch_array($result,MYSQL_NUM);; } echo "<script language="javascript" type="text/javascript"> var questions = new Array(100); for (var i = 0; i <100; i++) { questions[i] = new Array(6); } /*The following method of copying 2d php array to 2d javascript array is not working for ( var i = 0; i <= 99; i++) { questions[i]= ["<?php echo join("\", \"", $quest[i]); ?>"]; } */ /*The following method ,however,is working*/ questions[0]= ["<?php echo join("\", \"", $quest[0]); ?>"]; questions[1] = ["<?php echo join("\", \"",$quest[1]); ?>"]; questions[2] = ["<?php echo join("\", \"",$quest[2]); ?>"]; ....and so on </script>"; mysql_close($db_server); ?> Hi, Here is a working code to copy 2d php array to 2d javascript array. Code: <html> <head> <?php for($i = 0; $i < 3; $i++) { for($j = 0; $j < 2; $j++) {$quest[$i][$j] = $i*10+$j;} } ?> <script type="text/javascript"> var questions = new Array(3); for (var i = 0; i < 3; i++) { questions[i] = new Array(2); } questions[0] = ["<?php echo join("\", \"", $quest[0]); ?>"]; questions[1] = ["<?php echo join("\", \"", $quest[1]); ?>"]; questions[2] = ["<?php echo join("\", \"", $quest[2]); ?>"]; document.write(questions[0][0] + "<br />"); document.write(questions[0][1] + "<br />"); document.write(questions[1][0] + "<br />"); document.write(questions[1][1] + "<br />"); document.write(questions[2][0] + "<br />"); document.write(questions[2][1] + "<br />"); </script> </head> </html> Now,here's the thing.Notice these lines in the code questions[0] = ["<?php echo join("\", \"", $quest[0]); ?>"]; questions[1] = ["<?php echo join("\", \"", $quest[1]); ?>"]; questions[2] = ["<?php echo join("\", \"", $quest[2]); ?>"]; I would like to put these lines in a loop,something like for (var i = 0; i < 3; i++) { questions[i] = ["<?php echo join("\", \"", $quest[i]); ?>"]; } But even after a lot of efforts I am unable to do so,what am I doing wrong?Thanks Hi, i can't find the mistake in my little script hope someone can help me. PHP Code: <?php /* -------------------- read thumbfolder -------------------- */ function isRdyPfD($filename){ if ($filename == '.' || $filename == '..') { // To-Top-Dir return false; } $ext = explode(".",$filename); $ext = $ext[sizeof($ext) - 1]; $allowedformats = array ( 'jpg', 'png', 'jpeg', 'gif' ); return in_array($ext,$allowedformats); } function getPicsfromDir($dir){ /* array with names of the pictures in $dir */ if (is_dir($dir)) { if ($dh = opendir($dir)) { $filearray = array(); while (($file = readdir($dh)) !== false) { if (isRdyPfD($file) === true) { $filearray[] = $file; } } closedir($dh); return $filearray; } } else { return false; } } // End Function $thumbs = getPicsfromDir("./images/thumbs/"); /* -------------------- thumbfolder -------------------- */ echo "<div id='thumbslider'>\n"; echo "<ul id='thumbs'>\n"; for($i = 0; $i < count($thumbs); $i++){ echo "<li><img src=\"./images/thumbs/$thumbs[$i]\" onclick=\"thumbClick($i)\" /></li>\n"; } echo "</ul>\n"; echo "</div>\n"; /* -------------------- big size images folder -------------------- */ $bigSizeImages = getPicsfromDir("./images/"); //print_r($bigSizeImages); $jsValue = ''; for ($j=0; $j < count($bigSizeImages); $j++){ $jsValue = $jsValue . $bigSizeImages[$j]; if ($j < (count($bigSizeImages)-1)) { $jsValue = $jsValue . ","; } } ?> <script type="text/javascript"> images = new Array(<?php echo $jsValue ?>); function thumbClick(pos){ //alert(pos); alert(images[pos]); } </script> I can't trace the images array values? thanks for a feedback!!! I'm having major pains trying to figure this out. I'm kind of new to Javascript, I need to open a text file from an external server, store each line in an array, then search that array for a certain word (HIGH), and if it exists then write something to the webpage, and if not, write something else. Here is what I have so far: Code: <html> <head> <title>Test</title> <script> <!-- function test(x) { if (wxd1txt.readyState === 4 && wxd1txt.status === 200) { // Makes sure the document is ready to parse and Makes sure it's found the file. var wxd1text = wxd1txt.responseText; var wxd1array = wxd1txt.responseText.split("\n"); // Will separate each line into an array var wxd1high = wxd1array.toString(); //Converting the String content to String //var highsearchreg = new RegExp("HIGH"); //var wxd1high = wxd1array[x].search(highsearchreg); document.write(wxd1high); if (wxd1high.search("HIGH") >= 0){ document.write("HIGH RISK");} else { document.write("NO RISK");} } } //--> </script> </head> <body> Hi! <script> <!-- var Today = new Date(); var ThisDay = Today.getDate(); var ThisMonth = Today.getMonth()+1; var ThisYear = Today.getYear(); var Hour = Today.getHours(); var Day2 = Today.getDate()+1; var Day3 = Today.getDate()+2; if (navigator.appName != "Microsoft Internet Explorer") { ThisYear = ThisYear + 1900;} if (ThisMonth < 10) { ThisMonth = "0" + ThisMonth;} if (ThisDay < 10) { ThisDay = "0" + ThisDay;} if (Hour == 2 || Hour == 22 || Hour == 23 || Hour == 0 || Hour == 1) { var wxHourd1 = 0600} else if (Hour >= 3 && Hour <= 10) { var wxHourd1 = 1300;} else if (Hour >= 11 && Hour <= 13) { var wxHourd1 = 1630;} else if (Hour >= 14 && Hour <= 16) { var wxHourd1 = 2000;} else if (Hour >= 17 && Hour <= 21) { var wxHourd1 = 0100;} //var wxurld1 = "http://www.spc.noaa.gov/products/outlook/archive/"+ThisYear+"/KWNSPTSDY1_"+ThisYear+""+ThisMonth+""+ThisDay+""+wxHourd1+".txt"; var wxurld1 = "http://www.spc.noaa.gov/products/outlook/archive/2010/KWNSPTSDY1_201005101300.txt" //(High risk day for testing) //document.write(wxurld1); //Use this to verify this section is working if (window.XMLHttpRequest) { wxd1txt=new XMLHttpRequest(); } else // IE 5/6 { wxd1txt=new ActiveXObject("Microsoft.XMLHTTP"); } wxd1txt.open("GET", wxurld1, true); wxd1txt.onreadystatechange = test(); // --> </script> </body> </html> When added to a webpage, nothing shows up except the "Hi!" and there are no errors in the Javascript Console in Google Chrome. Is this possible with Javascript, and if so, what am I doing wrong or not doing? Also, I have 2 URLs, one is a text file that has the HIGH text I want for an example, the other is the current file, which shouldn't have HIGH in it (unless the weather in the US turns really bad) Ok lol don't mock me, I'm only new to javascript. I'm trying to get the text that contains "The Moderating Team" "Today's Active Topics" etc. an id to the div they are contained in. Here's my code so far: Code: <script type="text/javascript"> var c = getElementByClass("div"); if ( c.innerHTML.contains(" The Moderating Team ") ) { } </script> Any help? Oh and my site: http://stereo.b1.jcink.com |