JavaScript - Display Specific Results From An Array
I have this simple php array. The array will dynamically pull results from the db in the future.
PHP Code: <?php $dataArray = array ( 'id1' => array ( 'icon' => '<img src="images/piicon.png">', 'app' => 'GGP', 'timestamp' => date('m/d/y'), 'location' => 'Bellevue', 'comments' => 'It works!', ), 'id2' => array ( 'icon' => '<img src="images/piicon.png">', 'app' => 'Meijer', 'timestamp' => date('m/d/y'), 'location' => 'San diego', 'comments' => 'It works!', ), 'id3' => array ( 'icon' => '<img src="images/piicon.png">', 'app' => 'Point Inside', 'timestamp' => date('m/d/y'), 'location' => 'Boston', 'comments' => 'I guess its working? Maybe not exactly what we want yet though?!', ) ); echo json_encode($dataArray); ?> Currently if I have 100 results in my array, 100 results will be added to the table, 75 = 75 rows etc. What I am trying to plan out is a logical way to display one result from the array at a time. I am not looking for a chunk of jquery as an answer, better yet would be a plan/idea a programmer would you use to solve this. PHP Code: $(document).ready(function() { setInterval(function() { // get data $.ajax({ url: '/ajax/data.php', type: "GET", cache: false, error: function(data) { $("div#error").html('error: '+data); }, success: function(data) { var jsonObj = jQuery.parseJSON(data); jQuery.each(jsonObj, function(index, value) { var newRow = $("<tr><td>"+value.icon+"</td><td>"+value.app+"</td><td>"+value.timestamp+"</td><td>"+value.location+"</td><td>"+value.comments+"</td></tr>"); $("#mainTable tbody").prepend(newRow); }); } }); }, 5000); }); thanks Similar Tutorialsfrom my spry sub.menu tab, i'm trying to use "onclick" to post a new img in a specific div elsewhere on the page. <li><a class="MenuBarItemSubmenu" href="#">CPQC</a> <ul> <li><a href="#" onclick="document.getElementById('cpqcRange').src='images/cpqc/cpqcHot.png';">Hot</a></li> </ul> </li> <div id="cpqcRange"> <p> <img src="cpqcLocation.png" alt="cpqcLocation" name="cpqcLocation" width="504" height="360" id="cpqcLocation" /> </p> </div> i think i'm close, but something is wrong. can you just call up the div "cpqcRange" by name and slap a new img.src in there??????? cheers, Paul today's weather in Kalispell, MT, USA cold, brrrrr, not much snow, but it's coming soon it was about 18degF this morning Hi Within a classic asp webform (using vbscript) I would like part of the form (input boxes within table structure) to be specific/displayed depending on the users selection from the combo box in the row above. I think the best solution would be using Javascript can anyone suggest a solution or example code? Many thanks Sarah Hi to All, I have two menus, related each other, in this way: <head> var sum_db = new Object() sum_db["email1"] = [{value:"I01 - Problems of one level", text:"I01 - Problems of one level"}, {value:"I02 - Problems RDM", text:"I02 - Problems RDM"}, {value:"Free Text", text:"Free Text "}]; sum_db["email2"] = [{value:"I03 - Various", text:"I03 - Various"}]; // // function setIssue(chooser) { var newElem; var where = (navigator.appName == "Microsoft Internet Explorer") ? -1 : null; var Iss_Chooser = chooser.form.elements["iss_sum"]; while (Iss_Chooser.options.length) { Iss_Chooser.remove(0); } var choice = chooser.options[chooser.selectedIndex].value; var db = sum_db[choice]; if (choice == "email1") { newElem = document.createElement("option"); newElem.text = "Choose an issue ..."; newElem.value = "Choose Issue ..."; Iss_Chooser.add(newElem, where); } for (var i = 0; i < db.length; i++) { newElem = document.createElement("option"); newElem.text = db[i].text; newElem.value = db[i].value; Iss_Chooser.add(newElem, where); if ((choice == "email1") && (db[i].text.indexOf('Free Text')==0)) { document.getElementById("label_des").style.display=""; } else { document.getElementById("label_des").style.display="none"; } } } // </script> </head> <body> <form> <select size="1" name="mess" id="mess" onchange="setIssue(this)"> <option value="email1" selected>email1</option> <option value="email2">email2</option> </select> .... .... <select id="iss_sum" name="iss_sum"> <option value="<%=objRS("Issue_Summary")%>" selected><%=objRS("Issue_Summary")%></option> </select> <label for="iss_des" id="label_des" style="display:none; vertical-align:top">Description:<textarea id="iss_des" name="iss_des"><%=objRS("Issue_Description")%></textarea> </label> My problem is: I would like that if I select ONLY email1 and ONLY the option "Free Text", appears the textarea with label Description. Up to know if one selects email1, automatically the textarea appears near for every option; it seems that the condition of the if is not respected !!! Thanks a lot in advance !!! Hey. I have a string and I can return say, the fourth letter with output[3], but i can't assign a value to it for some reason: I am trying to make hang man Code: <!DOCTYPE html> <html> <head> <script src="jquery.min.js"></script> <script> $(document).ready(function(){ var word, output, wordLength, stringLength, newLetter, letters; var i, n, k, health, wcheck; word = "word"; output = ""; letters = ""; wordLength = word.length; for(i = 0; i < wordLength; i++){ output += "_"; } $("#inputLetters").keyup(function(){ newLetter = $("#inputLetters").val(); $("#inputLetters").val(""); letters += newLetter; wcheck = false; for(i = 0; i < wordLength; i++){ if(word[i] == newLetter){ wcheck = true; output[i] = newLetter; } } if(wcheck = false){ health++; } $("#letters").html(output + "<br />" + letters); }); }); </script> </head> <body> <span id="letters"> </span> <br /> <br /> <input id="inputLetters" type="text" /> </body> </html> Can anyone help me with a little project I'm been lumbered with? I've been given the task of building a carbon offset calculator What I need to do is have a webpage on a touchscreen kiosk that allows a visitor to the client enter their name/company/email address, plus select how they travelled to the premises and their departing post code. When they submit the form, I need it to email the details to the client so they can produce a nice little certificate saying how many trees have been planted to offset the visitors journey - but I also need it to display the details on screen before resetting itself for the next Prius driving visitor to use. I've got to the stage where I can EITHER capture all the details needed and email them OR capture all the details needed and calculate the distance travelled, KGs of CO2 expended and how many trees are needed and display them. I'm having difficulty getting it to do both! Thanks in advance! Well after much trial and error I come asking for help. I am trying to write a greasemonkey script that scans a page for all the values between certain <td> tags. When I used firebug it shows what I am looking for as <td class="username">THEUSERNAME</td> but when I view the source it just shows up as <td>THEUSERNAME</td> I want to create an array of the 100 <td>'s on the page that pertain to usernames but none of the other <td>'s I created a test page that mimicked the code, what I thought origionally, to be so I could test my script with ease. And it worked when there was an actually <td class="username"> This is what I have so far: Code: // ==UserScript== // //Displayable Name of your script // @name EXAMPLE // // brief description // @description EXAMPLE // //URI (preferably your own site, so browser can avert naming collisions // @namespace http://something.com // // Your name, userscript userid link (optional) // @author ME // //Version Number // @version 1.0 // // Urls process this user script on // @include http://example.com // ==/UserScript== var test = document.getElementsByClassName('username'); alert(test.length); test[5].style.color="yellow"; //Just to see if it actually worked Hi.. I have forms and I only need to input is the Demanded Qty, and from Demanded Qty that I input it will compute the demanded qty for each Item Code. Now my problem is I don't know on how can it possible that while i input the quantity it will also autodisplay the demanded qty for each materials. Noted: the Demanded Qty that will auto display is display only on the Demanded Qty you input per Items. For Example: On Item = P28 i input demanded qty, only on the ItemCode will display the output. and when i input on P30 the computation will display on the ItemCode for P30. 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 Quantity = document.getElementById('Quantity').value; var 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' onkeypress = 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> Thank you so much Hi, Apologies in advance but I have no experience of Javascript. I found the following 'Cut & Paste Google Internal Site Search script' in the Javascriptkit.com library - it works well and provides an easy solution for adding a search function to a website - code below Code: <script type="text/javascript"> // Google Internal Site Search script- By JavaScriptKit.com (http://www.javascriptkit.com) // For this and over 400+ free scripts, visit JavaScript Kit- http://www.javascriptkit.com/ // This notice must stay intact for use //Enter domain of site to search. var domainroot="www.javascriptkit.com" function Gsitesearch(curobj){ curobj.q.value="site:"+domainroot+" "+curobj.qfront.value } </script> <form action="http://www.google.com/search" method="get" onSubmit="Gsitesearch(this)"> <p>Search JavaScript Kit:<br /> <input name="q" type="hidden" /> <input name="qfront" type="text" style="width: 180px" />*<input type="submit" value="Search" /></p> </form> <p style="font: normal 11px Arial">This free script provided by<br /> <a href="http://www.javascriptkit.com">JavaScript Kit</a></p> However, if possible, I would like to display the results inside the website structure rather than on a new page - is there an easy way to do this? Thanks in advance for any help. I have a small form that I'm working on for a client. They want a form that their potential leads can fill out and then hit 'calculate rate'. Once this is done, the results should display on another page with a short summary of what their quote will be as well as some of the other information they filled out. It should also send an email to my client displaying the information that their lead just filled out. My only problem is I am not sure how to go about the calculation part. I know I would have to do an onSubmit, but how would I hide that calculation and then receive that number on another page. Here is the javascript for that form: Code: /* This source is shared under the terms of LGPL 3 www.gnu.org/licenses/lgpl.html You are free to use the code in Commercial or non-commercial projects */ //Set up an associative array //The keys represent the size of the cake //The values represent the cost of the cake i.e A 10" cake cost's $35 var practice_field = new Array(); practice_field["None"]=0; practice_field["Allergy and Immunology"]=4400; practice_field["Endocrinology"]=4400; practice_field["Pathology"]=4400; practice_field["Dermatology"]=4400; practice_field["Geriatrics"]=4400; practice_field["Physical Rehabilitation"]=4400; practice_field["Family Practice"]=6900; practice_field["General Practice"]=6900; practice_field["Internal Medicine"]=6900; practice_field["Oncology"]=6900; practice_field["Oral Surgery"]=6900; practice_field["Radiology"]=6900; practice_field["Gastroenterology"]=6900; practice_field["Infectious Disease"]=6900; practice_field["Nephrology"]=6900; practice_field["Ophthalmology"]=6900; practice_field["Pediatrics"]=6900; practice_field["Urology"]=6900; practice_field["Anesthesiology"]=9000; practice_field["Cosmetic Surgery"]=9000; practice_field["General Surgery"]=9000; practice_field["Neurology"]=9000; practice_field["Otolaryngology"]=9000; practice_field["Plastic Surgery"]=9000; practice_field["Vascular Surgery"]=9000; practice_field["Cardiology"]=9000; practice_field["Emergency Medicine"]=9000; practice_field["Gynecology"]=9000; practice_field["Orthopedic Surgery"]=9000; practice_field["Pain Management"]=9000; practice_field["Pulmonary Surgery"]=9000; practice_field["Neurological Surgery"]=9900; practice_field["Obstetrics"]=9900; //Set up an associative array //The keys represent the filling type //The value represents the cost of the filling i.e. Lemon filling is $5,Dobash filling is $9 //We use this this array when the user selects a filling from the form var society_member= new Array(); society_member["None"]=null; society_member["BCMA"]=0.10; society_member["DCMA"]=0.10; society_member["FOGS"]=0.10; society_member["FNS"]=0.10; society_member["PBCMS"]=0.10; society_member["FSPS"]=0.10; //This function finds the filling price based on the //drop down selection function getPracticeField() { var docPracticeField=0; //Get a reference to the form id="cakeform" var theForm = document.forms["cakeform"]; //Get a reference to the select id="filling" var selectedPracticeField = theForm.elements["practice"]; //set cakeFilling Price equal to value user chose //For example filling_prices["Lemon".value] would be equal to 5 docPracticeField = practice_field[selectedPracticeField.value]; //finally we return cakeFillingPrice return docPracticeField; } //This function finds the filling price based on the //drop down selection function getSelectedSociety() { var docSelectedSociety=0; //Get a reference to the form id="cakeform" var theForm = document.forms["cakeform"]; //Get a reference to the select id="filling" var selectedSociety = theForm.elements["society"]; //set cakeFilling Price equal to value user chose //For example filling_prices["Lemon".value] would be equal to 5 docSelectedSociety = society_member[selectedSociety.value]; //finally we return cakeFillingPrice return docSelectedSociety; } //candlesPrice() finds the candles price based on a check box selection function candlesPrice() { var candlePrice=0; //Get a reference to the form id="cakeform" var theForm = document.forms["cakeform"]; //Get a reference to the checkbox id="includecandles" var includeCandles = theForm.elements["includecandles"]; //If they checked the box set candlePrice to 5 if(includeCandles.checked==true) { candlePrice=0; } //finally we return the candlePrice return candlePrice; } function insciptionPrice() { //This local variable will be used to decide whether or not to charge for the inscription //If the user checked the box this value will be 20 //otherwise it will remain at 0 var inscriptionPrice=0; //Get a refernce to the form id="cakeform" var theForm = document.forms["cakeform"]; //Get a reference to the checkbox id="includeinscription" var includeInscription = theForm.elements["includeinscription"]; //If they checked the box set inscriptionPrice to 20 if(includeInscription.checked==true){ inscriptionPrice=0; } //finally we return the inscriptionPrice return inscriptionPrice; } function calculateTotal() { //Here we get the total price by calling our function //Each function returns a number so by calling them we add the values they return together var cakePrice = getPracticeField() + null - (getPracticeField() * getSelectedSociety()) + candlesPrice() + insciptionPrice(); //display the result var divobj = document.getElementById('totalPrice'); divobj.style.display='block'; divobj.innerHTML = "Your Pre-Paid Legal Defense Fee Will Be Around $"+cakePrice; } function hideTotal() { var divobj = document.getElementById('totalPrice'); divobj.style.display='none'; } If you look at the bottom you can see where the Function that Calculates everything is. Right now it calculates onClick. I just want it to calculate after the user has filled out the form completely and display that calculation on another page along with the rest of the information they inputted. 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'm trying to display a random message by making an array through values in an XML file and then displaying the info on the page. i want to have it so that a new message is generated each time the button is clicked with no repeats. here is what i have Code: function initial() { var xmlDoc; // First option for internet explorer 5 and 6, second option for firefox, internet explorer 7+ window.ActiveXObject ? xmlDoc = new ActiveXObject("Microsoft.XMLDOM") : xmlDoc = document.implementation.createDocument("","",null); xmlDoc.async = false; xmlDoc.load("quotes.xml"); // take the quote and author information from the xml file var pQuotes = xmlDoc.getElementsByTagName('quote'); var pAuthors = xmlDoc.getElementsByTagName('author'); // create arrays var aQuotes = new Array(); var aAuthors = new Array(); // put the quotes into the array for (i=0; i<pQuotes.length; i++) { aQuotes.push(pQuotes[i].childNodes[0].nodeValue); alert(pQuotes); } // put the authors into the array for (i=0; i<pAuthors.length; i++) { aAuthors.push(nAuthors[i].childNodes[0].nodeValue); } // Loop through arrays and print their quotes and authors for (var s in aQuote) { alert(aQuotes[s]); alert(aAuthors[s]); } } var Q = aQuotes.length; var quoteText = document.getElementById('aQuotes'); var authorText = document.getElementById('aAuthors'); var randomquote = Math.floor(Q * Math.random()); function quoter() { var randomquote2 = randomquote; while (randomquote == randomquote2) { randomquote = Math.floor(Q * Math.random()); } document.getElementById('quoteText').innerHTML = aQuotes[randomquote]; document.getElementById('authorText').innerHTML = " - " +aAuthors[randomquote]; quote.innerhtml = aQuotes[randomquote]; author.innerhtml = aAuthor[randomquote]; } navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false); </script> XML Code: <?xml version="1.0" encoding="utf-8" ?> <quotes> <theQuote> <quote>Over the years your bodies become walking autobiographies, telling friends and strangers alike of the minor and major stresses of your lives.</quote> <author>Marilyn Ferguson</author> </theQuote> <theQuote> <quote>In reality, serendipity accounts for one percent of the blessings we receive in life, work and love. The other 99 percent is due to our efforts.</quote> <author>Peter McWilliams</author> </theQuote> <theQuote> <quote>The secret of joy in work is contained in one word - excellence. To know how to do something well is to enjoy it.</quote> <author>Pearl Buck</author> </theQuote> <theQuote> <quote>The discovery of a new dish does more for human happiness than the discovery of a new star.</quote> <author>Anthelme Brillat-Savarin</author> </theQuote> <theQuote> <quote>When I was born I was so surprised I didn't talk for a year and a half.</quote> <author>Gracie Allen</author> </theQuote> </quotes> HTML Code: <body onload="initial()"> <div id="container"> <div id="header"> <h1>quotes</h1> </div> <div id="content"> <span id="quoteText"></span> <span id="authorText"></span> <br/> <br/> <input type="button" value="Click here for another quote" onclick="quoter()"/> </div> Hi everyone, i am developing a facebook application and here i am, struggling with this piece of code. I have this php query result he $id = $facebook->api(array('method' => 'fql.query', 'query' => "SELECT uid FROM user WHERE uid IN( SELECT uid FROM page_fan WHERE page_id='411133928921438' AND uid IN ( SELECT uid2 FROM friend WHERE uid1 = me() ))")); And i need to save it as an array like: var user_ids = [x,y,z] etc etc... I have used the json_encode but it isn't working... here is my code.. Code: var user_ids = <?php echo json_encode($id); ?>; How can i retrieve the query results, the id's in an array like i mentioned above? Please help me... Right now I am trying to grab all the links on a html page a store them in an array so that they can be accessed by a loop that makes sure that each one works. Right now I am not getting very far with it. If someone could help me I would be greatly appreciative.
The code below looks elementary, but it gives absurd results. Can you tell how I should have written it? I am slowly beginning to understand why it fails. But I do not understand why the JavaScript tutorials I've studied never warned against this trap. Any ship needs a list of crew members. The total number of persons onboard must be known too, for the case the ship sinks. We place these two properties in a prototype, so that we won't have to repeat them for each kind of ship. A passenger list is needed only if the ship is a passenger ship, so we decide not to place the passenger list in a prototype. Code: function Ship() { this.crew = []; this.persons = 0; } function PassengerShip(name) { this.name = name; this.passengers = []; } PassengerShip.prototype = new Ship; Passengers and crew arrive one by one shortly before departure. The first thing they do onboard is to check in: Code: Ship.prototype.checkin = function(list, person) { this[list].push(person); ++this.persons; } (Instead of the push function, we could as well have used a statement such as Code: this[list][ this[list].length ] = person; I have tried. Same wrong result.) Let us launch two passenger ships and check some persons in. Code: var msFloat = new PassengerShip("M/S Float"); msFloat.checkin("crew", "Captain"); msFloat.checkin("crew", "Cook"); msFloat.checkin("passengers", "Alice"); msFloat.checkin("passengers", "Bob"); var msFlawed = new PassengerShip("M/S Flawed"); msFlawed.checkin("crew", "Capt'n"); msFlawed.checkin("crew", "Sailor"); msFlawed.checkin("passengers", "Charlie"); The shipping company wants a report when everybody has checked in. But I'm not sure they will like it: Code: Ship.prototype.report = function() { function makeList(ship, list) { if (!ship[list]) return (ship.name + " has no list of " + list + ".\n"); if (!ship[list].length) return (ship.name + " has no " + list + ".\n"); return (list + ": " + ship[list].join(", ") + "\n"); } alert("\nPre-Departure Report For '" + this.name + "'\n\n" + makeList(this, "passengers") + makeList(this, "crew") + "\nNumber of persons onboard: " + this.persons + "\n\n"); } msFloat.report(); // OK: Alice, Bob as passengers; Captain, Cook as crew msFlawed.report(); // WRONG CREW: Captain, Cook, Capt'n, Sailor The number of persons (passengers + crew) is reported correctly for both ships, and so is the passenger list. But the "M/S Flawed" reports four crew members. Two of those never checked in on that ship. How can such a thing happen? What kind of blunder did I make? An "edit+execute" version of the code is available at bjarne.altervista.org/sailor.html together with a little testoutput, some considerations based on that testoutput, and a workaround (which is not the same as a solution - it looks ridiculous). It seems as if arrays placed in prototypes do not always work as expected. Can that be true? The testoutput suggests that JavaScript sometimes forgets to create a much-needed own property in the this object, and instead changes the prototype. But that sounds incredible, doesn't it? I am not too familiar with the deeper theory of JavaScript, and I hope to get a response. Here is the code concatenated and embedded: Code: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><title>Array In JavaScript Prototype</title></head> <body> <script type="text/javascript" language="JavaScript"> function Ship() { this.crew = []; this.persons = 0; } function PassengerShip(name) { this.name = name; this.passengers = []; } PassengerShip.prototype = new Ship; Ship.prototype.checkin = function(list, person) { this[list].push(person); ++this.persons; } Ship.prototype.report = function() { function makeList(ship, list) { if (!ship[list]) return (ship.name + " has no list of " + list + ".\n"); if (!ship[list].length) return (ship.name + " has no " + list + ".\n"); return (list + ": " + ship[list].join(", ") + "\n"); } alert("\nPre-Departure Report For '" + this.name + "'\n\n" + makeList(this, "passengers") + makeList(this, "crew") + "\nNumber of persons onboard: " + this.persons + "\n\n"); } var msFloat = new PassengerShip( "M/S Float" ); msFloat.checkin("crew", "Captain"); msFloat.checkin("crew", "Cook"); msFloat.checkin("passengers", "Alice"); msFloat.checkin("passengers", "Bob"); msFloat.report(); // OK: Alice, Bob as passengers; Captain, Cook as crew var msFlawed = new PassengerShip( "M/S Flawed" ); msFlawed.checkin("crew", "Capt'n"); msFlawed.checkin("crew", "Sailor"); msFlawed.checkin("passengers", "Charlie"); msFlawed.report(); // WRONG CREW: Captain, Cook, Capt'n, Sailor </script> </body> </html> I have spent much time struggling with this kind of error, which is reproducible in 5 different browsers. This is the first time I have been able to reproduce it in a form that can be presented to others. Is there a well-established programming practice that can prevent it? What do experienced JavaScript programmers do? Regards Bjarne Pagh Byrnak All, I have the following code: console.log("My num is: " + num); console.log("My lat is: " + lat); console.log("My lat length is: " + lat.length); console.log("My long is: " + long); When I get the output, I get the following: My num is: {"1":1,"2":2} My lat is: {"1":"40.59479899","2":"41.4599860"} My lat length is: 36 My long is: {"1":"-75.5549650","2":"-87.596430"} I'm confused on why the length is saying 36 when it's obviously two and the other output shows that??? Hello, another noob question for you: I have a function that requires the ability to count the number of entries in an array. I'm using the following to call my function inside an input tag: Code: onblur="javascript:check(this.name, this.value, 1, 10);" which for example is calling check('field1', 'foobar', 1, 10) Here is the javascript: Code: function check(name, value, min, max){ var errors=new Array(); if(value.length < min || value.length > max){ //checking against min/max length of value errors[name] = "Text field must not be blank."; errors["blabla"] = "array value 2"; //added for testing purposes alert(name+" : "+value); //returns "field1 : foobar" } alert(errors.length); // returns "0" } And when errors.length is alerted, it outputs 0. I can only figure that there is an issue when using custom named keys in an array, since this works when I use only integers, however, I have the need to use a custom key index as shown. Any ideas? Another thing that has been driving me crazy is that css positioning is handled differently by different browsers. JS is not my area, but I can do a lot with CSS, and I do, but cross browser compatibility is killing me. I can use an IF IE statement and only IE runs that segment of code, but I haven't been able to figure out out how to make ONLY firefox or ONLY opera or safari enact an encapsulated segment of code. The same type of IF statement doesn't work for them. Is there a single method using JS that works for all browsers? Thre is probably a very simple answer and I am just missing it somehow. I would like to display the elements in my array but it is NOT working. Here's my code: Code: <HTML> <HEAD> <TITLE>Test Input</TITLE> <script type="text/javascript"> function addtext() { var openURL=new Array("http://google.com","http://yahoo.com","http://www.msn.com","http://www.bing.com"); document.writeln('<table>'); for (i=0;i<=openURL.length-1;i++){ document.writeln('<tr><td>openURL[i]</td></tr>'); } document.writeln('</table>'); } </script> </HEAD> <body onload="addtext()"> </BODY> </HTML> Here's the ouput: Code: openURL[i] openURL[i] openURL[i] openURL[i] It should display: Code: http://google.com http://yahoo.com http://msn.com http://bing.com Any comments or suggestions are greatly apprecitated. thanks |