JavaScript - Retrieving Values From Arrays.
Similar TutorialsI had post this problem before, dealing with the shopping cart application. The application so far does everything that i would like it to do. I'm able to store and retrieve the cookies. But right now, my problem is extracting the individual values from the cookies and placing them into a table i have created. This is the format of the cookie when retrieved. ItemName = quantity$price. what i am trying to do is retrieve the quantity and price values from the cookie, and display that data into my table. the cookie is being created in my store page, and then retrieved and displayed in my cart page. here is the code for my store page store.html Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1- transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title> Store </title> <h1> My store </h1> <script type="text/javascript"> function retr(circle) { var cke = document.cookie.split(';'); var nameCk= name + "="; for(var i=0; i < cke.length; i++) { var c = cke [i]; while (c.charAt(0)==' ') c = c.substring(1, c.length); if (c.indexOf(nameCk) == 0) return c.substring(nameCk.length, c.length); } return null; } function createCookie() { var exdate = new Date(); exdate.setDate(exdate.getDate() +10); if (document.getElementById("circle").checked) { document.cookie = "Circle=" + document.getElementById ("quantity1").value + document.getElementById("price1").value + ";expires="+exdate.toGMTString(); } } function retrieve() { if (document.getElementById("circle").checked) { document.getElementById("ret").value = document.cookie; } } function Calc() { var fpri = document.getElementById("price1").value; var pri = fpri.substr(1); var qty = document.getElementById("quantity1").value; var spri = document.getElementById("price2").value; var pri2 = spri.substr(1); var qty2 = document.getElementById("quantity2").value; if (document.getElementById("circle").checked) { document.getElementById("total").value ='$' + Number(pri) * Number(qty); } else document.getElementById("total").value = '$' + Number(pri2) * Number(qty2); } </script> </head> <body> <table border = "1"> <tr> <td> <input type="checkbox" id="circle" /> Circle </td> <td> <img src="circle.jpg"> </img> </td> <td> Price: <input type="text" size="4" value = "$10.00" id="price1" name = "price1" /></td> <td> Quantity: <input type="text" size = "4" id="quantity1"/></td> </tr> <tr> <td> <input type = "checkbox" id="stickman" /> Stickman </td> <td> <img src = "stickman.gif"> </img> </td> <td> Price: <input type="text" size="4" value = "$5.00" id="price2" /> </td> <td> Quantity: <input type="text" size="4" id="quantity2" /> </td> </tr> </table> <br /> <input type = "button" value = "Add to cart" onclick="createCookie()"> <br /> <br /> <a href ="cart.html" > View Cart </a> <br /> <input type = "text" size = "8" id = "total" readonly = "readonly" /> Total <br /> <input type = "button" id = "calcu" value = "calc" onclick = "Calc ()" /> <input type = "button" value = "retrieve" onclick = "retrieve()" /> <input type = "text" readonly = "readonly" name = "ret" id = "ret"/> </body> </html> the calculate and retrieve buttons, and the readonly text boxes are there just so i know the cookie is being stored and retrieved, and that i'm able to get the total, which will be displayed on my cart page. here is the code for my cart page cart.html Code: <html> <head> <title> Cart </title> <h1> My cart </h1> <script type = "text/javascript"> function retr(circle) { document.getElementById("q2").value = document.getElementById("quantity1").value } function retrieve() { var quvalue = retr("circle") if (quvalue != false) { document.getElementById("q2").value = quvalue } document.getElementById("ret").value = document.cookie; } </script> </head> <body onload = "retrieve()"> <table border = "1"> <td>Stickman </td> <td><input type = "text" size = "8" id = "q2" readonly = "readonly" /></td> <td id ="p1"> price per </td> <td id ="t1"> total </td> <tr> </tr> <td> Circle </td> <td> quantity order </td> <td> price per </td> <td> total </td> <tr> </tr> <td colspan = "3"> TOTAL: </td> <td> total price </td> </table> <br /> <br /> <input type ="text" id = "ret" readonly = "readonly" /> <br / > <br /> <input type = "button" value = "Checkout"> <br /> <br /> <a href = "store.html" > Continue Shopping </a> </body> </html> the values that are supposed to be retrieved in the table are invoked using the onload event attribute which is suppose to call the retrieve() function. I am a beginner. I am trying to create a script to randomly assign recipients to givers for a Secret Santa. The participants are placed into groups. A giver cannot be assigned a recipient with whom he is grouped. I want to return all of the assignments in a table. I have made the following script. When I run it, it seems to get stuck in a loop. Any ideas why this might be? If you have any questions about how I want this thing to run, feel free to ask. Your help would be greatly appreciated. Code: <html> <head> <script type="text/javascript"> var giver = new Array(); giver[0] = new Array("CL","BL"); giver[1] = new Array("LP","JP","BP"); giver[2] = new Array("JO","MO"); giver[3] = new Array("JC","TC"); var recipient = new Array(); recipient[0] = new Array("none","none"); recipient[1] = new Array("none","none","none"); recipient[2] = new Array("none","none"); recipient[3] = new Array("none","none"); var string = "<table><tr><td>Giver</td><td>Recipient</td></tr>"; function chooseRecipient() { var x; for (x in giver) { var y; for (y in giver[x]) { var a = Math.floor(Math.random() * giver.length); while (recipient[a].indexOf("none") < 0 || a == x) { a = Math.floor(Math.random() * giver.length); } var b = Math.floor(Math.random() * giver[a].length); while (recipient[a][b] != "none") { b = Math.floor(Math.random() * giver[a].length); } recipient[x][y] = giver[a][b]; string += "<tr><td>" + giver[x][y] + "</td><td>" + recipient[x][y] + "</td></tr>"; } } string += "</table>"; document.write(string); } </script> </head> <body onload="chooseRecipient()"> </body> </html> I need to loop the alphabet and numbers 0-9 to initialize a few thousand arrays. This is for my site and is truly needed. http://www.thefreemenu.com I currently have every array written out and it takes up to much space in my .js file. The majority of my variables are empty but necessary and need to be there (including empty) for my site to work properly. Question is the last part Here's where I'm at. Code: var NewVarLetterOrNum = "a"; eval("_oneofseveralnames_" + NewVarLetterOrNum + "='this part works';"); alert(_oneofseveralnames_a); This creates the variable _oneofseveralnames_a='this part works' Code: var newArrayLetterOrNum = "a"; eval("_oneofseveralnames_" + newArrayLetterOrNum + "= new Array();"); alert(_oneofseveralnames_a) This creates the Array _oneofseveralnames_a=new Array(); and all the values in the array are null, but, now a variable like _nl_a[1]='something' can be used elsewhere because the array exists. This is all that is necessary for now because I can probably set all the variables to be blank with something like Code: i=1 while(i<=20){ _oneofseveralnames_a[i]="1-20"; i++ } alert(_oneofseveralnames_[20]); So now you have what I came to understand in the first few hours. Now to the hard part : ( I can't make multiple array's dynamically. I dont' know if its because I don't understand loops or arrays or what and its very fustrating. As for any answer you might be so kind as to provide, if you could dumb it down that would be greatly appreciated. Code: var newArray =new Array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z') i=1 while(i<=26){ eval("_nl_" + newArray[i] + "= new Array();"); i++ } alert(newArray[1]) // Is b, but alert(_nl_b) //I can't get _nl_b to exist, I tried everything including taking away the quotes around the letters in every test */ var _nl_a =new Array() var _img_a =new Array() var _h_a =new Array() var _r_a =new Array() var _m_a =new Array() var _yt_a =new Array() var _i_a =new Array() The above arrays are all the array _name_ parts I need but for example, a has 10 parts, a,p2_a,p3_a,.. p10_a. I need 10 pages for each letter of the alphabet and numbers 0-9 and a special all1, p2_all1 ... p10_all1. Overall 2200 arrays that need to be declared. Currently they are all written out. /* I think this is a relatively simple problem, instead of hard coding the latitude and longitude in map.setCenter I need it to read it in from an XML file, like the the markers do below (.getAttribute("lat") and .getAttribute ("lng")). I hope this makes sense, I've tried changing the code around but I can't seem to make it work. Any help appreciated. Code: // create the map var map = new GMap2(document.getElementById("map")); map.addControl(new GLargeMapControl()); map.addControl(new GMapTypeControl()); map.setCenter(new GLatLng( 49.4008,1.4941), 5); // Read the data from example.xml GDownloadUrl("example.xml", function(doc) { var xmlDoc = GXml.parse(doc); var markers = xmlDoc.documentElement.getElementsByTagName("marker"); for (var i = 0; i < markers.length; i++) { // obtain the attribues of each marker var lat = parseFloat(markers[i].getAttribute("lat")); var lng = parseFloat(markers[i].getAttribute("lng")); var point = new GLatLng(lat,lng); var html = markers[i].getAttribute("html"); var label = markers[i].getAttribute("label"); // create the marker var marker = createMarker(point,label,html); map.addOverlay(marker); } Hi gud mng, I have one problem... How to process textbox values/ call textbox values in JS through a Java program. My text box values are dates. I have to process these dates. Like in online banking we select day to know our transactions. After submitting we get results. remember my files are in my directory only. No need of database. My files are look like 20100929, 20100930, 20101001 For epoch_classes.js, epoch_styles.css u can download coding from this link : http://www.javascriptkit.com/script/...ch/index.shtml Code: Code: <html> <table width="900" border="0" cellpadding="10" cellspacing="10" style="padding:0"> <tr><td id="leftcolumn" width="170" align="left" valign="top"> <div style="margin-left:0px;margin-top:0px"><h3 class="left"><span class="left_h2">Select Option</span></h3> <a rel="nofollow" target="_top" href="day_wise.htm" >Day-wise</a><br /> <br /> <a rel="nofollow" target="_top" href="between.htm" >Between Days</a> <link rel="stylesheet" type="text/css" href="epoch_styles.css" /> <script type="text/javascript" src="epoch_classes.js"></script> <script type="text/javascript"> var cal1, cal2; window.onload = function () { cal1= new Epoch('epoch_popup','popup',document.getElementById('popup_container1')); cal2= new Epoch('epoch_popup','popup',document.getElementById('popup_container2')); }; /*............*/ function confirmation(f) { var startdate = f.fromdate.value var enddate = f.todate.value var myday=new Date() var yr=myday.getFullYear() var mn=myday.getMonth()+1 var dt=myday.getDate() var today="" var present, ys, ms, ds, ye,me,de, start, end if(mn < 10) { mn = "0" + mn } if(dt <10) { dt = "0" + dt } today= yr + "/" + mn + "/" + dt present=yr + "/" + mn + "/" +dt if (today < startdate ) { alert (" Start date should not be exceed to-day's date " + present ) startdate.focus() return false } if (today < enddate ) { alert (" End date should not be exceed to-day's date " + present ) enddate.focus() return false } if (today == startdate ) { alert(" You are selected to-days date as Starting day" ); } var answer = confirm("Do you want to continue ?") if (answer) { if( startdate < enddate) alert("Dates between " + startdate + " to " + enddate + " are confirmed" ) else alert("Dates between " + enddate + " to " + startdate + " are confirmed" ) } else { alert("Date not confirmed") window.location="to_date.htm"; } ys= startdate.substring(0,4); ms= startdate.substring(5,7); ds= startdate.substring(8,10); start=ys + "" + ms + "" +ds ye= enddate.substring(0,4); me= enddate.substring(5,7); de= enddate.substring(8,10); end=ye + "" + me + "" +de } /*.......................................................*/ </script> <div style="margin-left:100px;"> <body> <style type="text/css"> #conf { margin-left:115px; } </style> <td align="left" valign="top"> <table width="100" border="0" cellpadding="0" cellspacing="0"> <td style="padding-top:0px"> </table> <h4>From Date</h4> <form name= "formbet" id="placeholder" method="post" action="#" > <input id="popup_container1" type="text" name= "fromdate" maxlength="10" size="20"/> <td align="left" valign="top"> <table width="300" border="0" cellpadding="0" cellspacing="0"> <td style="padding-top:20px"> <h4>To Date</h4> <input id="popup_container2" type="text" name= "todate" maxlength="10" size="20"/> <br /> <br /> <input id="conf" type="button" onclick="confirmation(this.form)" value="Submit"> </form> </body> </html> In my coding, ys, ms, ds represents year starting, month starting, starting day... ye, me, de represents end... start,end gives file names in the format of yyyymmdd now i want to process files from 20100101 to 20100930 means from date is 2010/01/01 and to date is 2010/09/30 if i press submit button the files from 20100101 to 20100930 are processes here ys=2010 ms=01 ds =01 and ye=2010 me=09 de= 30 For this how do i call these textbox values (from date text box and todate) to another program (java) Thanks in advance. So basically, I have this side bar with a whole bunch of links and I wish to load content into a div directly across from it. The links will be hashes (eg example.com/#foo/bar), then the JavaScript loads the content either into a div and updates a SPAN with the page name. I only have the iFrame version so far, so can someone help me on how to improve this and actually load the content instead of an iFrame? So far I have this code: Code: <script> function goto(url) { if (location.hash != url) { window.location = url; document.getElementById("pgname").innerText = "loading..."; } } function setPage() { var hash = location.hash; if (hash=="#foo") { document.getElementById('pgname').innerHTML = 'Foo'; document.getElementById('pglocation').innerHTML = hash; window.frames['content'].location.href = "blablah/foo.php"; } if (hash=="#foo/bar") { document.getElementById('pgname').innerHTML = 'Foo</b> > <b>Bar'; document.getElementById('pglocation').innerHTML = hash; window.frames['content'].location.href = "doo/moo/23.htm"; } } </script> <body onhashchange="setPage();"> <a href="javascript: goto('#foo')">foo</a><br /> <a href="javascript: goto('#foo/bar')">foobar</a><br /> <a href="javascript: alert(location.hash + ' || ' + location);">Info</a><br /> <a href="javascript: goto(location.hash);">Goto</a><br /><br /> <b><span id="pgname">Home</span></b><br /> example.com/<span id="pglocation"></span><br /> <iframe id="content" src="index.php" /> HI I have set up a page passing information.. eg anything.htm?the text and I am trying to retrieve it into a form field ie pre fill a box. What I cant seem to work is to get the text after the ? into prefilled text for the field I can print it with document.write. I am trying to get it into (or something similar) <textarea rows="4" name="products" cols="49"> XXXX here text after htm? XXXX </textarea>. Hope this makes sense and I appreciate any help and time. Hello all, Sorry if this may seem like a silly question, I have searched but not really to sure how to word what I am searching for as I don't know if I am going the right way around it! Basically, I am looking to insert a keyword in to a javascript alert box when someone visits my website, so say they came from codingforums.com, it would say "Welcome, CodingForums.com Visitor". My keyword will be passed from the ad platform I am working with and shows up correctly in the tracking, so I'd imagine it's just a case of having the snippet of code for it to show in the alert, correct? If there is no keyword, I would just like it to say "Welcome Visitor" or something. How do I go about this? Thank you in advance for any help. Hi, I'm new to this forum so please forgive me on any errors I may have made. I am working on a simple site for the company that I work for that allows a customer to input a 5 digit code in and returns what prize they have won. I found some code on a website which done the trick but it doesn't work in Chrome and Safari. My Javascript knowledge is extremely limited but I think I've narrowed it down to the "document.implentation.createDocument" line although the few fixes I've found, I can't get to work. Here is the code I have at the moment before I applied the fixes (this works in FF and IE). Code: <script type="text/javascript"> window.onload = loadIndex; function loadIndex() { // load indexfile // most current browsers support document.implementation if (document.implementation && document.implementation.createDocument) { xmlDoc = document.implementation.createDocument("", "", null); xmlDoc.load("results.xml"); } // MSIE uses ActiveX { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.load("results.xml"); } } function searchIndex() { // search the index (duh!) if (!xmlDoc) { loadIndex(); } // get the search term from a form field with id 'searchme' var searchterm = document.getElementById("searchme").value; var allitems = xmlDoc.getElementsByTagName('item'); results = new Array; if (searchterm.length < 4) { alert("Please re-check and enter your 5 digit code"); } else { for (var i=0;i<allitems.length;i++) { // see if the XML entry matches the search term, // and (if so) store it in an array var name = allitems[i].lastChild.nodeValue; var exp = new RegExp(searchterm,"i"); if ( name.match(exp) != null) { results.push(allitems[i]); } } // send the results to another function that displays them to the user showResults(results, searchterm); } } // Write search results to a table function showResults(results, searchterm) { if (results.length > 0) { // if there are any results, write them to a table document.write('<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Untitled Document</title><link href="cno-competition.css" rel="stylesheet" type="text/css" /></head><body>'); document.write('<div id="container"><div id="logo"></div><div id="prizeContent"><img src="media/new-york.jpg" width="750" height="500" alt="New York" />'); for(var i=0; i<results.length; i++) { document.write('<h1>Congratulations</h1><p>You entered prize code <b><i>'+searchterm+'</i></b> and have won a <span style="font-weight:bold; color:#75ACC1">' + results[i].getAttribute("prize") + '</span>.</p>'); } document.write('<p>To claim your prize please contact the Complete Night Out team on 01908 544445.</p>'); document.write('</div></div></body></html>'); document.close(); } else { // else tell the user no matches were found var notfound = alert('No results found for '+searchterm+'! Please re-check and enter your 5 digit code'); } } </script> The fix I found added the below into the code but I couldn't get it to work using this. Link here. Code: var xmlhttp = new window.XMLHttpRequest(); xmlhttp.open("GET","results.xml",false); xmlhttp.send(null); xmlDoc = xmlhttp.responseXML.documentElement; Any help would be much appreciated. If you would like to see the site live please click here Thank you. Kishan I have a bunch of checkboxes like below that the user can check some or all and click the button and see the values of all the selected checkboxes. How can I do that? Code: <script> function alertValues(){ } </script> <input type="checkbox" class ="normal2" value="131971" name="list[]" > <input type="checkbox" class ="normal2" value="131973" name="list[]" > <input type="checkbox" class ="normal2" value="131975" name="list[]" > <input type="checkbox" class ="normal2" value="131977" name="list[]" > <input type="button" onClick="alertValues()" Here's my HTML: Code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" /> <title>The Happy Hoppin' Hotel</title> <script src="happyhoppin.js" language="javascript" type="text/javascript"></script> </head> <body> <h1>The Happy Hoppin' Hotel Checkout Page</h1> <h2>Fill out the form below to calculate balance due</h2> <form> Guest ID Number: <input type="text" id="guestID" /> <br /> <br /> Room Type: <select id="roomType"> <option></option> <option>Parlor</option> <option>Single</option> <option>Double</option> </select> <br /> <br /> Length of Stay: <input type="text" id="stayLength" /> <br /> <br /> Number of Drinks: <input type="text" id="drinkNumber" /> <br /> <br /> Number of Towels: <input type="text" id="towelNumber" /> <br /> <br /> Number of Flushes: <input type="text" id="flushNumber" /> <br /> <br /> Bug Complaints?: <br /> <form name="bugComplaintRadio"> <input type="radio" name="bugComplaint" value="No" />No</label> <br /> <input type="radio" name="bugComplaint" value="Yes" />Yes</label> <br /> </form> <br /> Customer Comments: <br /> <textarea name="customerComment" cols="50" rows="5">Enter your comments here...</textarea> <br /> <br /> <input type="button" onclick="calculateBill()" value="Calculate Bill"> </form> </body> </html> Here's my Javascript: Code: const parlorPrice = 80; const singlePrice = 100; const doublePrice = 150; const drinkPrice = 5; const towelPrice = 3; const flushPrice = 1; var guestID = 0; var roomPrice = 0; var stayLength = 0; var drinkNumber = 0; var towelNumber = 0; var flushNumber = 0; var totalDue = 0; var totalCharge = 0; function calculateBill(){ validateForm(); //roomType// if(roomType == "Parlor"){ roomPrice = parlorPrice; } if(roomType == "Single"){ roomPrice = singlePrice; } if(roomType == "Double"){ roomPrice = doublePrice; } //roomType// //drinkCharge// drinkCharge = drinkNumber * drinkPrice; //drinkCharge// //towelCharge// towelCharge = towelNumber * towelPrice; //towelCharge// //flushCharge// flushCharge = flushNumber * flushPrice; //flushCharge// //totalCharge// totalCharge = roomPrice + drinkCharge + towelCharge + flushCharge; //totalCharge// //**bugDiscount**// function getCheckedRadio() { bugValue = ""; bugLength = document.bugComplaintRadio.bugComplaint.length; var bugDiscount = 0; for (x = 0; x < bugLength; x ++) { if (document.bugComplaintRadio.bugComplaint[x].checked) { bugValue = document.bugComplaintRadio.bugComplaint[x].value; } } if (bugValue == "") { alert("You did not choose whether you had a bug complaint or not"); } if (bugValue = "No"){ bugDiscount = 0; } if (bugValue = "Yes"){ bugDiscount = 20; } } //**bugDiscount**// getCheckedRadio(); //totalDue// totalDue = totalCharge + bugDiscount //totalDue// displayBill(); } function validateForm(){ //guestID// guestID = parseInt(document.getElementById("guestID").value); if(isNaN(guestID)){ alert("Guest ID must be a number"); return; } if(guestID <= 0){ alert("Guest ID must be greater than zero"); return; } //guestID// //roomType// roomType = document.getElementById("roomType").value; if(roomType == ""){ alert("Room type must be selected"); return; } //roomType// //stayLength// stayLength = parseInt(document.getElementById("stayLength").value); if(isNaN(stayLength)){ alert("Length of stay must be a number"); return; } if(stayLength <= 0){ alert("Length of stay must be greater than zero"); return; } //stayLength// //drinkNumber// drinkNumber = parseInt(document.getElementById("drinkNumber").value); if(isNaN(drinkNumber)){ alert("Number of drinks must be a number"); return; } if(drinkNumber <= 0){ alert("Number of drinks must be greater than zero"); return; } if(drinkNumber > 25){ alert("Number of drinks has exceeded 25"); return; } //drinkNumber// //towelNumber// towelNumber = parseInt(document.getElementById("towelNumber").value); if(isNaN(towelNumber)){ alert("Number of towels must be a number"); return; } if(towelNumber <= 0){ alert("Number of towels must be greater than zero"); return; } //towelNumber// //flushNumber// flushNumber = parseInt(document.getElementById("flushNumber").value); if(isNaN(flushNumber)){ alert("Number of flushes must be a number"); return; } if(flushNumber <= 0){ alert("Number of flushes must be greater than zero"); return; } //flushNumber// //customerComment// customerComment = document.getElementById("customerComment"); //customerComment// } function displayBill(){ var newPage = "<html><head><title>Billing Summary</title></head>"; newPage += "<body><h1>Happy Hoppin Hotel</h1>"; newPage += "<h2>Guest Billing Statement</h2>"; newPage += "Guest Identification: #" + guestID; newPage += "<br />"; newPage += "Room Type: " + roomType; newPage += "<br />"; newPage += "Room Charge: $" + roomPrice; newPage += "<br />"; newPage += "Length of Stay: " + stayLength + " days"; newPage += "<br />"; newPage += "Drink Charge: $" + drinkCharge; newPage += "<br />"; newPage += "Towel Charge: $" + towelCharge; newPage += "<br />"; newPage += "Flushing Charge: $" + flushCharge; newPage += "<br />"; newPage += "Total Charge: $" + totalCharge; newPage += "<br />"; newPage += "Discount: $" + bugDiscount; newPage += "<br />"; newPage += "Total Due: $" + totalDue; newPage += "<br />"; newPage += "<h3>Come back and visit us again at the Happy Hoppin' Hotel!</h3>"; var z = window.open("","","width=400,height=500"); z.document.write(newPage); z.document.close(); } My question is, I've been spending countless hours trying to: 1. Make two radio buttons indicating "No" and "Yes", 2. Retrieve which selection the user has made, 3. Change the value of "bugDiscount" or the amount of money ($20 or $0) depending on which choice the user made; $0 for No & $20 for Yes. 4. Subtract the value of bugDiscount (0 or 20) from the totalCharge to get TotalDue I know I'm close, but I've tried any number of variations in my code and I still can't seem to get it right. Can anyone help? Hi, What's a good way/ideal data structure to achieve this? The objective of the code/function is to map user-inputted strings into a pair of specific, hard-coded strings. For example, say the user types "firefox" or "ff", or "fx". The output would be the pair ["browser", "mozilla"], for example. I'm currently using a multidimensional array, but it feels inefficient and I'm having trouble mapping an arbitrary number of inputs into 2 outputs. Code: var strings = [ ["input1", "output1a"], ["input2", "output1a"], ["input3", "output1a"], ["input1", "output1b"], ["input2", "output1b"], ["input3", "output1b"] ]; How should I map the elements ["input1", "input2", "input3"] => ["output1a", "output1b"] ? Another method I used previously was a massive switch statement. This fulfills my needs, but I'm not sure about the efficiency (though if I remember correctly, switch statements become more efficient as size grows, since it uses a hash table?). Code: switch (input) { case "ff": case "firefox": case "fx" : case "ffox": return ["browser", "mozilla"]; case "ie": case "internet explorer": return ["browser", "microsoft"]; ... } Hi could someone help with this javascript. i dont know where to start with the script which is in bold. Program to report the results of an election. // candidates var candidateArray = ['Mr R Green...', 'Ms O Brown...', 'Ms Y Black...', 'Mr G White...', 'Ms B Grey....','Ms I Blue....', 'Mr V Pink....']; // online votes var onlineVotesArray = [21,47,23,11,56,47,30]; // paper votes var paperVotesArray = [12,4,20,11,5,4,17]; // total votes -- to be initialised below var totalVotesArray; // Add code to // -- initialise totalVotesArray with a new empty array of the same size as candidateArray // -- use a for loop to add the online and paper votes for each candidate and store the result at the corresponding position in the total votes array. Hi. I am fairly new to JavaScript. I am having some troubles with arrays. I am using Chrome 12 beta. Here is a brief version of the code I am having trouble with Code: var array=new Array() array[0]=new Array() array[0][1]=new Array() var array[0][1]=[ 3, 1, 4, 1, 5, 9, 2, 6, 5, ... ]; I do not want to use "array[0][1][n]" because my array has too many items to do that and it is just plain annoying to change the numbers that way. I get an error on the "var buffers[0][1]=[" line saying: "Uncaught SyntaxError: Unexpected token [" What is the problem in my code? Thank you ahead of time. ---mint Code: <HTML> <HEAD> <TITLE>Listing 4.4</TITLE> <SCRIPT TYPE="text/javascript"> //DEFINE METHOD function displayInfo() { document.write("<H1>Employee Profile: " + this.data[0] + "</H1><HR /><PRE>"); document.writeln("Employee Number: " + this.data[1]); document.writeln("Social Security Number: " + this.data[2]); document.writeln("Annual Salary: " + this.data[3]); document.write("</PRE>"); } //DEFINE METHOD TO GET EMPLOYEE INFORMATION function getInfo() { var menu="0-Exit/1-Name/2-Emp. #/3-Soc. Sec. #/4-Salary"; var choice=prompt(menu,"0"); if (choice != null) { if ((choice < 0) || (choice > 4)) { alert ("Invalid choice"); this.getInfo(); } else { if (choice != "0") { this.data[choice-1]=prompt("Enter information",""); this.getInfo(); } } } } //DEFINE OBJECT function employee() { this.data = new Array(4); this.displayInfo=displayInfo; this.getInfo=getInfo; } newEmployee=new employee(); </SCRIPT> </HEAD> <BODY> <SCRIPT TYPE="text/javascript"> newEmployee.getInfo(); newEmployee.displayInfo(); </SCRIPT> </BODY> </HTML> I am currently taking a Javascript certification course, this is a exercise given (final code) I don't completely understand what is going on though, could someone explain to me Code: this.data[choice-1]=prompt("Enter information",""); that part? I don't understand why, [choice-1] I don't fully understand why an array is even needed here? First of all thank you for reading my thread and giving time to help me. Here goes my question: How to sort this array? MY PRIORITY COLORS array: ------------ green , yellow ALL COLORS array : <---- this will be your main array. ----------------------- pink , green , orange THE RESULTS: ( the results after you sort) (Not sorted by alphabetically, but sorted by the priority colors) ---------------- green , pink , orange I hope you could help me solve this javascript sorting problem. Thank you! I have a choice when creating a new API that I would like other peoples opinions on. Do I use a single Array or Multiple arrays such as: Code: array[1][1] = "ID[56]NAME[Hello World]START[10]"; OR Code: ID[1][1] = 56; Name[1][1] = "Hello World"; Start[1][1] = 20; The API is used for animations so is very heavy work, but would using around 15 multidimensional arrays be too much and a single one be preferable??? Thanks Hey, I'm working on a problem and what I need the program to do is to add up the numbers in the array NOT add up how many numbers there are. There are 5 total numbers that a user will input. The counting of the numbers will be in a seperate method which will then return to the main. Then be displayed through system.out.println. I don't know where I am going wrong any help? Thanks! Code: import javax.swing.*; import java.util.*; public class Question10 { public static void main (String []args) { //declares Scanner keyboard = new Scanner(System.in); int [] myNums = new int[5]; for (int i=0; i < myNums.length; i++) { System.out.println ("Please Enter Data"); myNums[i]= keyboard.nextInt(); } } //end main public static int getTotal(int inArray) { int a,b,c,d,e,f; f = a+b+c+d+e; return f; } }//end class I have a quick question with multiple array and random numbers. If i generate my random numbers in one array, how would i take a selection of those numbers and put them in another array? Ex: array 1: 25, 34, 38, 40, 22, 49 want to move numbers between 30 and 50 to another array. array 2: 34, 38, 40, 49 is it as simple as for loops and if statements setting the conditions? do i use a sorting method? (selection? bubble?) any help would be appreciated. |