JavaScript - Array Problem
I have been beating my head against the wall trying to figure this out for hours. It seems like it should be so easy, but here is my code:
Code: var tempMyPlayersArray = document.getElementsByClassName("player"); var myPlayersArray = new Array(); for (var p=0; p<playerColumnTeamArray.length; p++) { var stripPlayerColumnElement = playerColumnTeamArray[p].innerHTML.stripTags(); var pMatches = stripPlayerColumnElement.match(/(.*?) \((.*?) - (.*?)\)/); if(pMatches) myPlayersArray.push(pMatches[1]); } //This yields "Tony Romo" GM_log(myPlayersArray[0]); //This yields "false". GM_log((myPlayersArray[0]) == 'Tony Romo'); Note that stripTags() removes all of the html tags and leaves you with the folowing (or similar) for every element: Tony Romo (Dal - QB) So my overall question is why that last GM_log statement in the code is yielding false. I have made sure that the elements are all strings (using toString()), checked for white space issues (using repace()), and made sure the regex is working okay. No matter what though, I get false even though "Tony Romo" is clearly the only string in myPlayersArray[0]. Thanks! Similar TutorialsHi, New member, not really well versed in JS, and need help with the following. What is supposed to happen is the script will take today's day and then check the array to see if the date falls within a certain range of dates, and then return the appropriate items. Could someone please have a look at the code and see why it isn't working. Thanks in advance. George BTW; This is a stripped down version. Code: <script > // For months 0 = January var ch_y_S = "2010"; //X-mass season start; year var ch_m_S = "11"; //X-mass season start; month var ch_d_S = "25"; //X-mass season start; day var ch_y_E = "2011"; //X-mass season end; year var ch_m_E = "0"; //X-mass season end; month var ch_d_E = "9"; //X-mass season end; day var ot1_y_S = "2011"; var ot1_m_S = "0"; var ot1_d_S = "10"; var ot1_y_E = "2011"; var ot1_m_E = "2"; var ot1_d_E = "8"; var le_y_S = "2011"; var le_m_S = "2"; var le_d_S = "9"; var le_y_E = "2011"; var le_m_E = "3"; var le_d_E = "23"; var ad = "Advent"; var ch = "Christmas"; var ot = "Ordinary Time"; var le_ = "Lent"; var eas = "Easter"; var purple = PURPLE; var white = WHITE; var green = GREEN; var today = new Date(); var a = new Array ( { start: new Date(ch_y_S,ch_m_S,ch_d_S), end: new Date(ch_y_E,ch_m_E,ch_d_E,23,59,59), season: ch, txtColor:whi }, { start: new Date(ot1_y_S,ot1_m_S,ot1_d_S), end: new Date(ot1_y_E,ot1_m_E,ot1_d_E,23,59,59), season: ot, txtColor:gre }, { start: new Date(le_y_S, le_m_S,le_d_S), end: new Date(le_y_E, le_m_E,le_d_E,23,59,59), season: le_, txtColor:pur } ); var whatz = " "; var whatz1 = " "; for (i = 0; i < a.length; i++) { if ((today >= a[i].start) && (today <= a[i].end)) { whatz = a[i].color; whatz1 = a[i].season; } } document.write(whatz ) document.write('<br />' ) document.write(whatz1 ) </script Hi all, I am mixing googles geolocation with it's local search API. This sounds complicated but I think my problem is primarily one involving passing a value to an array. Here is my code Code: <script type="text/javascript"> var lat,lon; var scrnText; function main() { scrnText = document.getElementById('message'); if (navigator.geolocation) { scrnText.innerHTML = "acquiring your position..."; navigator.geolocation.getCurrentPosition(reportLatLon, function(error) { scrnText.innerHTML = "Couldn't acquire location (error "+error.code+"). "; }); } else { scrnText.innerHTML = "geolocation API not available!"; } } function reportLatLon(pos) { lat = pos.coords.latitude; lon = pos.coords.longitude; accuracy = Math.round(pos.coords.accuracy); scrnText.innerHTML="your location is " + lat + ", " + lon + " to "+ accuracy + " metres accuracy"; } </script> <script src="http://www.google.com/jsapi?key=AIzaSyA5m1Nc8ws2BbmPRwKu5gFradvD_hgq6G0" type="text/javascript"></script> <script type="text/javascript"> google.load('search', '1'); var localSearch; function searchComplete() { document.getElementById('content').innerHTML = ''; if (localSearch.results && localSearch.results.length > 0) { for (var i = 0; i < localSearch.results.length; i++) { var p = document.createElement('p'); var a = document.createElement('a'); var b = document.createElement('b'); var c = document.createElement('c'); a.href = localSearch.results[i].url; a.innerHTML = localSearch.results[i].title; b.innerHTML = "<br>" + localSearch.results[i].streetAddress; c.innerHTML = "<br>" + localSearch.results[i].city + "," + localSearch.results[i].region; p.appendChild(a); p.appendChild(b); p.appendChild(c); document.body.appendChild(p); } } } function onLoad() { localSearch = new google.search.LocalSearch(); var lat,lng,str navigator.geolocation.getCurrentPosition(handler); function handler(position) { lat = pos.coords.latitude; lng = pos.coords.longitude; str = lat + "," + lng; localSearch.setCenterPoint(str); } localSearch.setSearchCompleteCallback(this, searchComplete, null); localSearch.execute('cinema'); google.search.Search.getBranding('branding'); } google.setOnLoadCallback(onLoad); </script> </head> <!-- when this html page is loaded by a browser, it calls the 'main' javascript function --> <body onload="main()"> <h1>Geolocation Demo</h1> <h2>1. GeoLocation API</h1> <!-- this is where the html object updates text displayed to the user --> <span id="message"></span> <div id="branding" style="float: left;"></div><br /> <div id="content"></div> </body> All I want to do is pass the previous "lat,lon" value from the geolocation, into the "localSearch.setCentrepint part. As you will see I have tried using the following Code: Code: var lat,lng,str navigator.geolocation.getCurrentPosition(handler); function handler(position) { lat = pos.coords.latitude; lng = pos.coords.longitude; str = lat + "," + lng; localSearch.setCenterPoint(str); } but this will not work. I am a php coder so let me apologise in advance if i have worded this confusingly. Thanks in advance Dan Hi: I was trying to post in flowplayer forum but... Anyway, the code below works fine when run with browser called from Coffee Cup HTML editor. Files are played as requested from button onClick events. All files called and all ref files are on hosting server. When I put this page on the server and click the first button, the files play fine. When I then click thge second button, the files called by the first button play again. If I then click the second button, the files called by button 2 play. If I then click button 5, the files called by button 2 play again. The previous config is somehow being stored somewhere and called. I have added this and that as you can see in the code to try to rid the old config but to no avail: playerConfig = null playerConfig.playlist =[]; should clear it. delete playerConfigplaylist[0]; Should clear it. and thinking it was bumped to [1] delete playerConfigplaylist[1]; Should clear that. So I think the old playerConfig.playlist should be gone but apparently not so. I have reviewed: jquery.min.js, flowplayer-3.2.6.min.js and flowplayer.playlist-3.0.8.js and cannot see any cause to this behavior though I am not a js ace. Any insight appreciated. Best regards <code> <script> var mediaPlayer = null; var playerConfig = null; function createPlayerConfig () { playerConfig = null; playerConfig = { log: { level: 'debug' } , play: null, plugins: { controls: { url: 'https://www.jala-mi.org/gmfiles/flowplayer.controls-3.2.5.swf', bottom: 0, height: 24, backgroundColor: "#2d3e46", backgroundGradient: "low", fontColor: '#ffffff', timeFontColor: '#333333', autoHide: 'never', play:true, volume:true, mute:true, time:true, stop:true, playlist:true, fullscreen:true, scrubber: true } } } }; function changePlaylist(newplaylist,no_of_items) { playerConfig.playlist = []; delete playerConfig.playlist[0]; for(i=0; i < no_of_items; i++) { playerConfig.playlist[i] = newplaylist; } delete playerConfig.playlist[1]; createPlayer(); // reload player with new playlist mediaPlayer.play(); // start the newly loaded clip sequence* } function createPlayer() { if(mediaPlayer != null) { if(mediaPlayer.isLoaded()) { mediaPlayer.unload(); mediaPlayer = null; } } $f("player", { src:"https://www.jala-mi.org/gmfiles/flowplayer-3.2.7.swf" }, playerConfig ); mediaPlayer = $f("player"); } function loadandplay(intro, movie) { var presentation = {url: movie , duration: 0, autoPlay: true, autoBuffering: false, fadeInSpeed: 8000, fadeOutSpeed: 5000, title: 'JPD 02/28/2011',playlist: [{url: intro , duration: 0, position: 0, fadeInSpeed: 5000, fadeOutSpeed: 8000, autoPlay: true, autoBuffering: true, }] }; createPlayerConfig(); changePlaylist(presentation, 1); }; </script> </code> html <code> <div id="side"> <br><br> <input type="button" class="plbtn" value="November 2010" style="background-color:#0D4A80; color:#fff" onClick="javascript:loadandplay('https://www.jala-mi.org/gmfiles/Intro112210.flv', 'https://www.jala-mi.org/gmfiles/collections112210.flv')"> <br> <input type="button" class="plbtn" value="January 2011" style="background-color:#0D4A80; color:#fff" onClick="javascript:loadandplay('https://www.jala-mi.org/gmfiles/intronone.flv', 'https://www.jala-mi.org/gmfiles/')"> <br> <input type="button" class="plbtn" value="February 2011" style="background-color:#0D4A80; color:#fff" onClick="javascript:loadandplay('https://www.jala-mi.org/gmfiles/Intro22811.flv', 'https://www.jala-mi.org/gmfiles/jpd_3.flv')"> <br> <input type="button" class="plbtn" value="March 2011" style="background-color:#0D4A80; color:#fff" onClick="javascript:loadandplay('https://www.jala-mi.org/gmfiles/Intro32811.flv', 'https://www.jala-mi.org/gmfiles/assets32811.flv')"> <br> <input type="button" class="plbtn" value="April 2011" style="background-color:#0D4A80; color:#fff" onClick="javascript:loadandplay('https://www.jala-mi.org/gmfiles/intronone.flv', 'https://www.jala-mi.org/gmfiles/')"> <br> <input type="button" class="plbtn" value="May 2011" style="background-color:#0D4A80; color:#fff" onClick="javascript:loadandplay('https://www.jala-mi.org/gmfiles/intronone.flv', 'https://www.jala-mi.org/gmfiles/')"> <br> <input type="button" class="plbtn" value="September 2011" style="background-color:#0D4A80; color:#fff" onClick="javascript:loadandplay('https://www.jala-mi.org/gmfiles/intronone.flv', 'https://www.jala-mi.org/gmfiles/')"> <br> <input type="button" class="plbtn" value="October 2011" style="background-color:#0D4A80; color:#fff" onClick="javascript:loadandplay('https://www.jala-mi.org/gmfiles/intronone.flv', 'https://www.jala-mi.org/gmfiles/')"> <br> <input type="button" class="plbtn" value="November 2011" style="background-color:#0D4A80; color:#fff" onClick="javascript:loadandplay('https://www.jala-mi.org/gmfiles/intronone.flv', 'https://www.jala-mi.org/gmfiles/')"> <br> </div> </code> Hey all, first, if I missed this in my search, I apologize. Now on to the problem at hand. I'm reading an xml file of html links into a webpage I'm building on the intranet. I have assigned each of a particular element of that xml file to a specific location within a javascript array. Then I built a second javascript array and assigned the value of the first array to second array using the .toString(); method. Here's an example of what I've got so far: Code: var linkArray = new Array(); linkArray[0] = (xmlDoc.getElementsByTagName("link")[0].childNodes[0].nodeValue); linkArray[1] = (xmlDoc.getElementsByTagName("link")[1].childNodes[0].nodeValue); linkArray[2] = (xmlDoc.getElementsByTagName("link")[2].childNodes[0].nodeValue); linkArray[3] = (xmlDoc.getElementsByTagName("link")[3].childNodes[0].nodeValue); linkArray[4] = (xmlDoc.getElementsByTagName("link")[4].childNodes[0].nodeValue); linkArray[5] = (xmlDoc.getElementsByTagName("link")[5].childNodes[0].nodeValue); linkArray[6] = (xmlDoc.getElementsByTagName("link")[6].childNodes[0].nodeValue); linkArray[7] = (xmlDoc.getElementsByTagName("link")[7].childNodes[0].nodeValue); var pageArray = new Array(); pageArray[0] = linkArray[0].toString(); pageArray[1] = linkArray[1].toString(); pageArray[2] = linkArray[2].toString(); pageArray[3] = linkArray[3].toString(); pageArray[4] = linkArray[4].toString(); pageArray[5] = linkArray[5].toString(); pageArray[6] = linkArray[6].toString(); pageArray[7] = linkArray[7].toString(); I have put documentDOTwriteln statements in at various places to test the values of both arrays to be sure they are the same and they are. Now, later in the code, I'm loading an iframe that targets a specific element of the second array for the page link. It does this through a variable called currentPage thus: theIframe.src = pageArray[currentPage]; where currentPage is previously assigned a value pointing to an element in the array. For example currentPage = 0;. I'm trying to replace the original code which looks like this and works: Code: var pageArray = new Array(8); pageArray[0] = "html/chapters/chapter1_Introduction/chapter1.html"; pageArray[1] = "html/chapters/chapter2_Change-Location/chapter2.html"; pageArray[2] = "html/chapters/chapter3_Change-Manager/chapter3.html"; pageArray[3] = "html/chapters/chapter4_Change-Salary/chapter4.html"; pageArray[4] = "html/chapters/chapter5_Change-Assignment/chapter5.html"; pageArray[5] = "html/chapters/chapter6_Termination/chapter6.html"; pageArray[6] = "html/chapters/chapter7_Request-Access-to-MSS/chapter7.html"; pageArray[7] = "html/chapters/chapter8_Summary/chapter8.html"; with the contents of the xml file so I can load different pages into a template. I don't understand what I'm doing wrong. Can anyone point me in the right direction? I believe my xml is parsing correctly since I can do a documentDOTwriteln and see the contents when placed into an array. Am I wrong on this? Any and all help you can give is greatly appreciated! M I have two arrays that are tied together Ink1Data[][InkID] and Ink1Data[][Ink1Desc] I also have this Javascript code to validate it: Code: var chksink1 = document.getElementsByName("Ink1Data[][InkID]"); for (var i = 0; i < chksink1.length; i++) { switch (chksink1[i]) { case (chksink1.value=1); var i1Desc = "Ink1Data["+i+"][Ink1Desc]"; if (validate_required(i1Desc,"Please fill in a trim size.")==false) {i1Desc.focus();return false;} break; case (chksink1.value=2); var i1Desc = "Ink1Data["+i+"][Ink1Desc]"; if (validate_required(i1Desc,"Please fill in folding instructions.")==false) {i1Desc.focus();return false;} break; case (chksink1.value=3); var i1Desc = "Ink1Data["+i+"][Ink1Desc]"; if (validate_required(i1Desc,"Please fill in scoring instructions.")==false) {i1Desc.focus();return false;} break; } } basically, I want to count how many are in the array (will be the same number for both) and then depending on the value of the first array, validate the second and kick an appropriate error if necessary. it should be pretty easy, but I can't seem to get the code to work. Is there anyone that could please help me figure this out? Thank you! Hey guys I got a problem with my program, it converts a name to initial example: Jordy Derp ==> J.D. but i always get an undefined in front of it http://i43.tinypic.com/2qu12jn.png Code: addEventListener("load", init, false); function init() { var naam = new initialen(prompt("geef een naam in")); var tijdelijk = "" var naamArray = new Array(); var perm = "" function initialen(naam) { if (naam.indexOf(' ') >= 0) { naamArray = naam.split(" ") for (var i = 0; i < naamArray.length; i++) { perm += naamArray[i].charAt(0) + "." } alert(perm) } else { alert("False") } } } btw it also checks for spaces so u need to type 2 names Thanks in advance Hi, I'm new to javascript and have a small but annoying problem with an array. The script rotates a randomly selected banner from an array and changes the banner every few seconds. The problem is that when the page is first loaded the word 'undefined' displays next to the first banner. When the second banner is displayed everything works fine. Here is the function I am using Code: function randomBanner() { var myBanners=new Array(3); var i = Math.floor(Math.random() * 3); myBanners[0]="image 1"; myBanners[1]="image 2"; myBanners[2]="image 3"; document.getElementById('banners').innerHTML = myBanners[i]; setTimeout("randomBanner()",5000 ); } and here is the html Code: <head> <script type="text/javascript" src="rotator.js"></script> </head> <body> <div id="banners"> <script type="text/javascript">document.write(randomBanner());</script> </div> </body> I have tried declaring the variables and even the array itself outside the function to no avail. I have set up a test page so you can view the problem here Please can someone help? Code: var rollnav = []; rollnav[0] = new Image ; rollnav[0].src ="buttons/button 1 suits.png"; rollnav[1] = new Image; rollnav[1].src = "buttons/button 2 suits.png"; rollnav[2] = new Image; rollnav[2].src ="buttons/button 1 dresses.png"; rollnav[3] = new Image; rollnav[3].src ="buttons/button 2 dresses.png"; rollnav[4] = new Image; rollnav[4].src ="buttons/button 1 christening.png"; rollnav[5] = new Image; rollnav[5].src ="buttons/button 2 christening"; rollnav[6] = new Image; rollnav[6].src ="buttons/button 1 Acessories.png"; rollnav[7] = new Image; rollnav[7].src ="buttons/button 2 Acessories.png"; rollnav[8] = new Image; rollnav[8].src ="buttons/button 1 home.png"; rollnav[9] = new Image; rollnav[9].src ="buttons/button 2 home.png"; rollnav[10] = new Image; rollnav[10].src ="buttons/button 1 contact us.png"; rollnav[11] = new Image; rollnav[11].src ="buttons/button 2 contact us.png"; rollnav[12] = new Image; rollnav[12].src ="buttons/button 1 links.png"; rollnav[13] = new Image; rollnav[13].src ="buttons/button 2 links.png"; function SwapOutsuit(){ document.suitnav.src = rollnav[1].src; return true; } function SwapBacksuit(){ document.suitnav.src = rollnav[0].src; return true; } function SwapOutdress(){ document.dressnav.src = rollnav[3].src; return true; } function SwapBackdress(){ document.dressnav.src = rollnav[2].src; return true; } function SwapOutchris(){ document.chrisnav.src = rollnav[5].src; return true; } function SwapBackchris(){ document.chrisnav.src = rollnav[4].src; return true; } function SwapOutaccess(){ document.accessnav.src = rollnav[7].src; return true; } function SwapBackaccess(){ document.accessnav.src = rollnav[6].src; return true; } function SwapOuthome(){ document.homenav.src = rollnav[9].src; return true; } function SwapBackhome(){ document.homenav.src = rollnav[8].src; return true; } function SwapOutcus(){ document.cusnav.src = rollnav[11].src; return true; } function SwapBackcus(){ document.cusnav.src = rollnav[10].src; return true; } function SwapOutlink(){ document.linknav.src = rollnav[13].src; return true; } function SwapBacklink(){ document.linknav.src = rollnav[12].src; return true; } hi im trying to create a series of rollover buttons for my site that can be used on all pages. im using the above array to switch the button images the problem is they all work up until number 9 then they just display the image set as the original image and dont change on mouse over. i try declaring an array with more than 9 spaces it doesn't seem to make a difference ive tried the new array format to with no avail. any help would be greatly appreciated. i have included my code which is embedded in my html to call the function below. Code: <A href="coolkids formal contact us.html" onMouseOver="SwapOutcus()" onMouseOut="SwapBackcus()"><img src="buttons/button 1 contact us.png" name="cusnav" align="left" ></A> <A href="information.html" onMouseOver="SwapOutlink()" onMouseOut="SwapBacklink()"><img src="buttons/button 1 links.png" name="linknav" align="left" ></A> Hello, I've a checkbox validation script to check for at least one ckeck. Code: <script type="text/javascript"> function chkChecks(){ isChecked=false alert(document.forms["form1"]["checked[]"].length); for(var i=0;i<document.forms["form1"]["checked[]"].length;i++){ if(document.forms["form1"]["checked[]"][i].checked){ isChecked=true } } if(isChecked){ document.forms["form1"].submit() } else{ alert('Please select a checkbox') } } </script> for the form Code: <form name="form1" action="test.php"> <input type="checkbox" name="checked[]" value="1"> <input type="checkbox" name="checked[]" value="2"> <input type="checkbox" name="checked[]" value="3"> <input class="button_140" type="button" value="Check" onclick="chkChecks()"> </form> It works well for more than one checkboxes, but these are generated dynamically by PHP and if there is only one checkbox, document.forms["form1"]["checked[]"].length returns 'undefined'. Can I modify this to work in all cases? thanks, art. Hi.. I have problem on how can I automatically display the output from the computation (Demanded Qty * Quantity), after or while I input Demanded Qty. I mean I input Demanded Qty, on below it will display the output also beside the SubItems. Sorry, if i post again my problem, because I have no idea on how can I solve this problem. here is my code: PHP Code: <?php error_reporting(0); date_default_timezone_set("Asia/Singapore"); //set the time zone $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); ?> <html> <title>Stock Requisition</title> <head> <link rel="stylesheet" type="text/css" href="kanban.css"> <script type="text/javascript"> function compute_quantity(){ var DemandedQty = document.getElementById('DemandedQty').value; var SubQty = document.getElementById('SubQty').value; var Quantity = document.getElementById('Quantity').value; SubQty = (DemandedQty * Quantity); } </script> </head> <body> <form name="stock_requisition" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div> <table> <thead> <th>Items</th> <th>Sub Items</th> <th>Item Code</th> <th>Demanded Qty</th> <th>UoM</th> <th>Class</th> <th>Description</th> <th>BIN Location</th> </thead> <?php $DemandedQty = $_POST['DemandedQty']; $sql = "SELECT DISTINCT Items FROM bom_subitems ORDER BY Items"; $res_bom = mysql_query($sql, $con); while($row = mysql_fetch_assoc($res_bom)){ $Items = $row['Items']; $Items_ = substr($Items, 12, 3); echo "<tr> <td style='border: none;font-weight: bold;'> <input type='name' value='$Items_' name='Items_[]' id='Items' readonly = 'readonly' style = 'border:none;width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;'></td> <td style='border:none;'> </td> <td style='border:none;'> </td> <td style='border: none;'><center><input type='text' name='DemandedQty[]' id='DemandedQty' value='' size='12' onkeyup = compute_quantity()></center></td> </tr>"; $sql = "SELECT Items, SubItems, ItemCode, UoM, Class, Description, BINLocation, Quantity FROM bom_subitems WHERE Items = '$Items' ORDER BY Items"or die(mysql_error()); $res_sub = mysql_query($sql, $con); while($row_sub = mysql_fetch_assoc($res_sub)){ $Items1 = $row_sub['Items']; $SubItems = $row_sub['SubItems']; $ItemCode = $row_sub['ItemCode']; $UoM = $row_sub['UoM']; $Class = $row_sub['Class']; $Description = $row_sub['Description']; $BINLocation = $row_sub['BINLocation']; $Quantity = $row_sub['Quantity']; echo "<input type='hidden' name='Quantity' id='Quantity' value='$Quantity'>"; echo "<tr> <td style='border: none;'> <input type='hidden' value='$Items1' id='Items1' name='Items1[]'></td> <td style='border: none;'> <input type='text' name='SubItems[]' value='$SubItems' id='SubItems' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;'></td> <td style='border: none;'> <input type='text' name='ItemCode[]' value='$ItemCode' id='ItemCode' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;'></td> <td style='border: none;'><center><input type='text' name='SubQty[]' id='SubQty' value='' size='12' style></center></td> <td style='border: none;' size='3'> <input type='text' name='UoM[]' value='$UoM' id='UoM' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='3'></td> <td style='border: none;'> <input type='text' name='Class[]' value='$Class' id='Class' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;'></td> <td style='border: none;'> <input type='text' name='Description[]' value='$Description' id='Description' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size= '30'></td> <td style='border: none;'> <input type='text' name='BINLocation[]' value='$BINLocation' id='BINLocation' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;'></td> </tr>"; } } ?> </table> </div> </form> </body> </html> If you don't understand my issue feel free to ask me for further understanding. I'm sorry again I really need to solve this and i tried to google but I can't find the solution. Thank you so much Code: <html> <body> <script type="text/javascript"> var Items = new Array Items [0] = ["a", "b"]; Items [1] = ["c", "d"]; var i = 0; if(Items [i++][0] == "c"){ document.write("hello"); } </script> </script> <body> </body> </html> so im trying to search an array with this function its not working i tried using firebug but it showed no errors. I think its the i++ part i want to increment i each time it tries it. WAIT SORRY I SOLVED IT I solved it you can put in Pistol or shotgun for name Code: <html> <body> <script type="text/javascript"> var Items = new Array Items [0] = ["Pistol", "50", "2000"]; Items [1] = ["shotgun", "5000","1000"]; var i = 0; function chek(){ if(Items [i][0] == document.getElementById("name").value){ document.getElementById("a").value = Items [i] [1]; document.getElementById("acc").value = Items [i] [2]; i=0; } else { i++ } } </script> </script> <body> Dammage<input type="text" id="a" /> <br/> ACC<input type="text" id="acc" /> <br/> Name<input type="text" id="name" /> <br/> <input type="button" onclick="chek();" value="Chek" /> </body> </html> Is there anyway to make it more streamline so you dont have to click to increment? I am very new to javascript. I have a problem getting to any element from this form generated by the jsp page using struts. Please show me how to get to item[0].totalAmount for example, so that I can create a function to calculate the calculateTotal(). So far, when I do the alert, it is only valid up to document.myForm.item; the document.myForm.item[0] is invalid according to the alert. Any help is very much appreciated. function calculateTotal(){ alert(document.myForm.item); } <form name="myForm" method="post" action="/myAction.do"> <table id="display" border="1"> <tr> <th scope="col" id="totalAmount">Total Amount</th> <th scope="col" id="adjustmentAmount>Adjustment Amount</th> <th scope="col" id="newAmount">NewAmount</th> </tr> <tr> <td><input type="text" name="item[0].totalAmount" id="totalAmount" value="100" readonly="readonly"></td> <td><input type="text" name="item[0].adjustmentAmount" id="adjustmentAmount" value="" onblur="javascript:calculateTotal();" readonly="readonly"></td> <td><input type="text" name="item[0].newAmount" id="newAmount" value="" readonly="readonly"></td> </tr> <tr> <td><input type="text" name="item[1].totalAmount" id="totalAmount" value="350" readonly="readonly"></td> <td><input type="text" name="item[1].adjustmentAmount" id="adjustmentAmount" value="" onblur="javascript:calculateTotal();" readonly="readonly"></td> <td><input type="text" name="item[1].newAmount" id="newAmount" value="" readonly="readonly"></td> </tr> </table> </form> I'm writing a simple Chess Record keeping app (still ), and i'm having a problem with the Screen.X and Screen.Y variables to compare with the coordinate variables stored in an Array. The project is a little large, so here's the live version (on my website). Though it will only work if you run it from your local disk. http://daomingjin.googlepages.com/ScoreMate.html the zip archive of this is he http://daomingjin.googlepages.com/ScoreMatev1.zip the main JavaScript function file is he http://daomingjin.googlepages.com/Core.js the particular function in question is this: Code: var PieceThere = isPieceHere(ClosestX, ClosestY); function isPieceHere(x, y) { // Test to see if there is an Element at point x,y for (var i = 0; i < 32; i++) { if (PieceLocationXcoord[i] == x) { if(PieceLocationYcoord[i] == y) { // There is a piece there var Result = "True"; } } } return Result; } i have placed alert() boxes in many places in the code above, and i can tell the following: the function is being activated the coordinates of x and y are able to be accessed inside the function the arrays called PieceLocationYcoord and PieceLocationXcoord both have the values in them that are returned by the ClosestX and ClosestY function however, every time , the function continues to return "Undefined". I have even tried manually setting var Result = "True" inside the last if-then block, and still returns undefined. i have also tried using the alert box inside this function (before the variable return Result; is called) and still get undefined as the message from the alert box. Hi guys, I'm trying to write a function such that it can be called, with a particular string specified in the call, and the function will then search a pre-defined array ("pages") of webpage URLs and headers in the form ["[www.sampleurl1.com] Sample Header 1. ", "[www.sampleurl2.com] Sample Header 2. "]; etc. etc., to see if the aforementioned string occurs in the "header" part of any of the indexes of the "pages" array, and then if it does, to alert "Found in x,y,z" where x y and z are the indexes of the "pages" array in which the specified string was found to occur. Here is what I have so far: Code: var pages=["[www.lboro.ac.uk] Loughborough University. ", "[www.oxford.ac.uk] Oxford University. "]; var founds=[] function findIdxsC(s){ for(i=0;i<pages.length;i++) if((pages[i].substring(pages[i].indexOf("]") + 1,pages[i].lastIndexOf("."))).match(/s/)) founds.push(pages[i]) } var array=founds.filter(findIdxsC) var arr2str=array.toStr; alert("Found in "+arr2str); findIdxsC("nIvERsi"); In theory, the above example should alert "Found in 0,1" because I have used the "match" command (so the search is case-insensitive) and the string "niversi" is found in the "header" parts of indexes 0 and 1. However, what it actually alerts is "Found in undefined". As far as I can see the problem lies with either the if-statement(and the associated command to "push" the indexes of "pages" for which the condition applies, to a new array, "founds") or with the filter and toString commands used towards the end. Perhaps it is one of these, or perhaps there is something else I am missing? Either way I would appreciate it if anyone could identify what in my code is causing the "Found in undefined" alert and suggest how I could rectify it, as it's causing me a bit of a headache Many thanks I'm almost finished with this app for XUL / HTML Table Generation, and i have a really strange problem... The HTML strings in the Arrays can be changed, and the HTML file saved, and the HTML page reloaded, and the changes will render. However, i have one array, no matter what i change the HTML strings to, it refuses to render the changes made to the HTML strings. It's quite confusing... the array in question is Code: // Humidor InnerHTML HumidorInnerHTML[0] = "<img src='NoImage.gif' style='height:100px; width:100px;'>"; HumidorInnerHTML[1] = "<input type='textbox' id='Others_Caption" + HumidorIndex + "'>"; HumidorInnerHTML[2] = "<input type='textbox' value='85' id='Others_Height" + HumidorIndex +"'>"; HumidorInnerHTML[3] = "<input type='textbox' value='85' id='Others_Width" + HumidorIndex +"'>"; HumidorInnerHTML[4] = "<img src='NoImage.gif' style='height:100px; width:100px;'>"; HumidorInnerHTML[5] = "<img src='NoImage.gif' style='height:100px; width:100px;'>"; HumidorInnerHTML[6] = "<img src='delete.png' onClick=DeleteRow('" + HumidorIndex + "','Humidor_Table');>"; HumidorInnerHTML[7] = "<img src='add.png' onClick=AddRow('" + HumidorIndex + "','Humidor_Table');>"; and the function that generates the HTML Table on the fly (and adds the cell data to them) is he Code: function AddRow(index, DIV) { MyTable = document.getElementById(DIV); var newCell; var newRow = MyTable.insertRow(index); var Length; switch (DIV) { case "Intro_Table" : Length = IntroInnerHTML.length; break; case "Image_Table" : Length = ImageInnerHTML.length; break; case "Watch_Table" : Length = WatchInnerHTML.length; break; case "Others_Table" : Length = OthersInnerHTML.length; break; case "Humidor_Table" : Length = HumidorInnerHTML.length; break; } for (var i = 0; i < Length; i++) { newCell = newRow.insertCell(i); switch (DIV) { case "Intro_Table": newCell.innerHTML = IntroInnerHTML[i]; break; case "Image_Table": newCell.innerHTML = ImageInnerHTML[i]; break; case "Watch_Table": newCell.innerHTML = WatchInnerHTML[i]; break; case "Others_Table": newCell.innerHTML = OthersInnerHTML[i]; break; case "Humidor_Table": newCell.innerHTML = WatchInnerHTML[i]; break; } } // Update the Index Counters switch (DIV) { case "Intro_Table": IntroIndex++; break; case "Image_Table": ImageIndex++; break; case "Watch_Table": WatchIndex++; break; case "Others_Table": OthersIndex++; break; case "Humidor_Table": HumidorIndex++; break; } } when the page is loaded, the Init() function is started, that code is he Code: function Init() { AddRow(1, "Intro_Table"); AddRow(1, "Image_Table"); AddRow(1, "Watch_Table"); AddRow(1, "Humidor_Table"); AddRow(1, "Others_Table"); } Did i miss something? there must be something i've over looking. I have even tried isolating some other external JS, and CSS includes that i have, and isolating them has no change in the result. the html file is live he http://kevinjohnson.clanteam.com/XML...anageSite.html thanks Hi everyone I'm having a hard time, wrapping my head around an array sort+combine function. I have an array which would look somewhat (these are simplified numbers) like this Code: TestArray = [ ["222222","1"], ["222222","1"], ["222222","1"], ["333333","1"] ["111111","1"], ["000000","2"], ["111111","2"], ["111111","2"], ["222222","20"], ]; I got it as far as to be sorted like this: Code: SortedArray = [ ["000000","2"], ["111111","1"], ["111111","2"], ["111111","2"], ["222222","1"], ["222222","1"], ["222222","20"], ["222222","1"], ["333333","1"] ]; And from there to this: Code: BadlyMergedArray = [ ["000000","2"], ["111111,"1","2"], ["222222","1","20","1"], ["333333","1"] ]; But I want to end up with this: Code: MergedArray = [ ["000000","2"], ["111111","1","2"], ["222222","1","20"], ["333333","1"] ]; So the first part of the inner arrays is the first item to be sorted and combined by. After that, the smaller numbers have to do practically the same, while staying in the correct order under the first sort. I'm only a spare time programmer, and my code is probably one of the most confusing pieces of code ever written. I am assuming that this is some fairly easy stuff for one of you guys. I can post my code, but I think there's a much easier solution to it, so I wanted to see if someone can point me in the right direction, or show me how this is properly done. Thanks so much! here's to hoping! patrick/shootingpandas 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. 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. 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? |