JavaScript - Show Max And Min Values In A Array List
Hi, I'm trying to find out the min and max values of randomly generated values in a array list. Its a checkout system that randomly add a customer to a queue and does the same to remove a customer depending on a randomly generated number. Ive managed to figure out the mean of the queue but can only display the total values added to the list rather than display when the queue was at it biggest value. If anyone can point me in the right direction it would be greatly appreciated.
___________________________________________________________________ import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedList; import java.util.ListIterator; import java.util.Queue; import java.util.Random; public class Checkout { private Queue<String> tillQueue; private int rndNumber; private int currentLen; private ArrayList <Integer>lengthList; private Random r; public Checkout() { tillQueue = new LinkedList<String>(); currentLen = 0; //current queue length lengthList = new ArrayList <Integer>(); r= new Random(); } public void simulation() { System.out.println("Time" + "\t" + "Rnd" + "\t" +"Queue Status"); for (int t=2; t<10; t++) { rndNumber =r.nextInt(6)+1; if (rndNumber==2 || rndNumber==4 || rndNumber==6) { tillQueue.add(String.valueOf(t)); currentLen++; } else if ((rndNumber==1 || rndNumber==3) && !tillQueue.isEmpty()) { tillQueue.remove(); currentLen--; } else if(rndNumber==5) { //do nothing } if(tillQueue.isEmpty()) { System.out.println(t + "\t" + rndNumber + "\t" + "Queue is empty"); } else { System.out.println(t + "\t" + rndNumber + "\t" + tillQueue.toString()); } lengthList.add(new Integer(currentLen)); } } public double CalculateMeanLength() { double mean=0.0; int sumOfLengths = 0; for (int i = 0; i<lengthList.size();i++) { sumOfLengths=sumOfLengths+(Integer)lengthList.get(i).intValue(); } mean = (double)sumOfLengths/lengthList.size(); return mean; } public int ShowMax() { int max = 0; //i know its going to be a for loop of some kind but not sure how to do it// } ----------------------------output via controller================ Time Rnd Queue Status 2 6 [2] 3 5 [2] 4 3 Queue is empty 5 5 Queue is empty 6 1 Queue is empty 7 5 Queue is empty 8 5 Queue is empty 9 4 [9] mean length = 0.375 max length = 3 //the max length here should be 1 =========================================== Thanks in advance for your help Similar Tutorialshi, i am currently working on aptana stuidio Nokia WRT to create a mobile widget. the projects requires the retrieval of data from a database. I've created a java servlet in eclipse to connect and execute query to the database. In aptana, i'm using js file and html file. i am able to connect to the servlet, process the data (split it) and store in an array to display the retrieved data on screen. But now i am facing problems to put the retrieved data (array) into a drop down list for selection. can i do it in a js file? thanks =) My goal is that when I click on the submit button, I just want to display an alert box with the values selected, and also look at this in the console.log. Can anyone help me? Thanks. Code: <html> <head> </head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(init); function init() { $ ("#t").submit(function() { var g = showCheckedValues(); console.log(g); alert(g); }); function showCheckedValues() { // Gather all values of checked checkboxes with name "bedrooms". var checked = $('input[name=bedrooms]:checked').map(function() { return this.value; }).get(); }} </script> <body> <form id="t"> <input type="checkbox" name="bedrooms" value="1">1 bedroom<br> <input type="checkbox" name="bedrooms" value="2">2 bedroom<br> <input type="checkbox" name="bedrooms" value="3">3 bedroom<br> <input type="checkbox" name="bedrooms" value="4+">4+ bedroom<br> <input type="submit" name="save-changes"></input> </form> </body> </html> Hi. Now I know this is a fairly easy task, but I need to show the random div from a selection of 10 which all have the same class. I am not able to do this using unique IDs as the divs will be created by the end user as a repeating region from Adobe contribute. So I'll have a list looking something like the following but I only want one to show. Any ideas? Code: <div class="mydiv">Line Number One</div> <div class="mydiv">Line Number Two</div> <div class="mydiv">Line Number Three</div> <div class="mydiv">Line Number Four</div> <div class="mydiv">Line Number Five</div> <div class="mydiv">Line Number Six</div> <div class="mydiv">Line Number Seven</div> <div class="mydiv">Line Number Eight</div> <div class="mydiv">Line Number Nine</div> <div class="mydiv">Line Number Ten</div> It adds fine when any number but 12.3 is used if 12.3 is used however it gives 54.099999999999994 var liu = [10.6,11.2,9.4,12.3,10.1]; var calculateTotal= function(raceTimes){ var totalTime; var raceTime = raceTimes[0]; var i =0; for (i = 0; i< 4; i++){ raceTime = raceTime+raceTimes[i]; totalTime = raceTime; } return totalTime; }; var liuTotal = calculateTotal(liu); console.log(liuTotal); Hi, I have a dynamically generated list of which contain div's with a class of product. I want to only display 6 random products out of the whole list on page load and hide the rest. I am quite new to javascript so some help would be much appreciated. Thanks hi, the following function shows a list of Counties populates by a PHP page: Code: $.getJSON('http://www.mypubspace.com/dashtest/countyjson.php', function(data){ var myhtml = '<ul>'; for(i=0; i<data.length; i++) { myhtml += '<li>' + data[i].County + '</li>'; } myhtml += '</ul>'; $("#countyshow").html(myhtml); }); I would like to now, when a user clicks on a County, they are shown a list of pubs based on that County (so, I'll create a new PHP page WHERE County = 'County' or something?!) at the moment, when a user clicks on a County this function is passed: Code: function gopublist(event) { var stackLayout = document.getElementById('stackLayout').object; // Replace with id of StackLayout stackLayout.setCurrentView('view4'); } So, passing a value through so I can modify the SQL in the PHP page to filter the counties?! Please help? Hi, I doing my project in Netbeans, and I have this .java page, that sets and gets a html form where there are textboxes and drop down lists, as far as I know, although getElementById() is a javascript code, it can be used in my .java page, but I do not know how to implement it. What I'm supposed to do is to get the values from the drop down list and save them to a database that I've already have. Code: HtmlPage page = null; page.getElementById(id); but because I do not know what should the id be since the .java page is not a jsp page and the drop down list values cannot be retrieved directly. Need help here, thanks. hi, I would like to show a list of pubs in a town that the user has selected from the drop down list http://www.mypubspace.com/dashtest/order.html it is all there working but in a different way If you type Brighton into the Town search, it shows a list of pubs in that town, GREAT! If you click the 'show towns list' link, a drop down appears, (this is where my problem is) When you click the town, I would like to get the list of pubs in that town basically get rid of the form where you type in the box and click the button here is my code HTML and Javascript Code: <html> <body> <script language="javascript" type="text/javascript"> <!-- //Browser Support Code function ajaxFunction(){ var townRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari townRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ townRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ townRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server townRequest.onreadystatechange = function(){ if(townRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxDiv'); ajaxDisplay.innerHTML = townRequest.responseText; } } var name = document.getElementById('name').value; var county = document.getElementById('county').value; var town = document.getElementById('town').value; var queryString = "?name=" + name + "&county=" + county + "&town=" + town; townRequest.open("GET", "http://www.mypubspace.com/dashtest/pubs.php" + queryString, true); townRequest.send(null); } function townlistFunction(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxTownlist'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } } ajaxRequest.open("GET", "http://www.mypubspace.com/dashtest/town-select.php", true); ajaxRequest.send(null); } function countylistFunction(){ var ajaxRequest; // The variable that makes Ajax possible! try{ // Opera 8.0+, Firefox, Safari ajaxRequest = new XMLHttpRequest(); } catch (e){ // Internet Explorer Browsers try{ ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){ // Something went wrong alert("Your browser broke!"); return false; } } } // Create a function that will receive data sent from the server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ var ajaxDisplay = document.getElementById('ajaxCountylist'); ajaxDisplay.innerHTML = ajaxRequest.responseText; } } ajaxRequest.open("GET", "http://www.mypubspace.com/dashtest/county-select.php", true); ajaxRequest.send(null); } function MM_jumpMenu(targ,selObj,restore){ //v3.0 eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'"); if (restore) selObj.selectedIndex=0; } //--> </script> <a href="#" onClick="townlistFunction();">show towns list</a> <a href="#" onClick="countylistFunction();">show counties list</a> <div id="ajaxTownlist"></div> <div id="ajaxCountylist"></div> <form name='myForm'> Pub Name: <input type='text' id='name' /> <br /> County: <input type='text' id='county' /> <br /> Town: <input type='text' id='town' /> <input type='button' onclick='ajaxFunction()' value='Query MySQL' /> </form> <div id='ajaxDiv'></div> </body> </html> here is my pubs.php code Code: <?php $dbhost = "xxx"; $dbuser = "xxx"; $dbpass = "xxx"; $dbname = "xxx"; //Connect to MySQL Server mysql_connect($dbhost, $dbuser, $dbpass); //Select Database mysql_select_db($dbname) or die(mysql_error()); // Retrieve data from Query String $name = $_GET['rsPubName']; $sex = $_GET['rsTown']; $wpm = $_GET['rsCounty']; // Escape User Input to help prevent SQL Injection $name = mysql_real_escape_string($name); $town = mysql_real_escape_string($town); $county = mysql_real_escape_string($county); //build query $query = "SELECT * FROM pubs WHERE rsTown = '$town'"; $qry_result = mysql_query($query) or die(mysql_error()); //Build Result String $display_string = "<table>"; $display_string .= "<tr>"; $display_string .= "<th>Region</th>"; $display_string .= "<th>Pub Name</th>"; $display_string .= "<th>Town</th>"; $display_string .= "<th>County</th>"; $display_string .= "</tr>"; // Insert a new row in the table for each person returned while($row = mysql_fetch_array($qry_result)){ $display_string .= "<tr>"; $display_string .= "<td>$row[Region]</td>"; $display_string .= "<td>$row[rsPubName]</td>"; $display_string .= "<td>$row[rsTown]</td>"; $display_string .= "<td>$row[rsCounty]</td>"; $display_string .= "</tr>"; } $display_string .= "</table>"; echo $display_string; ?> here is my town_select.php code Code: <?php $dbhost = "xxx"; $dbuser = "xxx"; $dbpass = "xxx"; $dbname = "xxx"; //Connect to MySQL Server mysql_connect($dbhost, $dbuser, $dbpass); //Select Database mysql_select_db($dbname) or die(mysql_error()); // Retrieve data from Query String $town = $_GET['rsTown']; // Escape User Input to help prevent SQL Injection $town = mysql_real_escape_string($town); //build query $query = "SELECT DISTINCT rsTown, COUNT(PUBID) As PubCount FROM pubs GROUP BY rsTown ORDER BY rsTown ASC"; $qry_result = mysql_query($query) or die(mysql_error()); // Insert a new row in the table for each person returned $display_string .= "<form name=\"form3\" method=\"post\" action=\"\">"; $display_string .= "<select name=\"menu2\" onChange=\"MM_jumpMenu('parent',this,0)\" class=\"textbox\">"; $display_string .= "<option value=\"\">Search by Town...</option>"; while($row = mysql_fetch_array($qry_result)){ $display_string .= '<option value="rsTown='.$row['rsTown'].'" onclick=\"ajaxFunction()\" id=\"town\">'.$row['rsTown'].' ('.$row['PubCount'].')</option>'; } $display_string .= "</select>"; $display_string .= "</form>"; echo $display_string; ?> Hi Chaps, I have a dynamic list menu: PHP Code: <?php $currentCat = ''; $first = true ;?> <ul> <?php do { if ($currentCat != $row_rsCategory['catname']) { if (!$first) { echo "\n</ul>\n</li>\n"; } $currentCat = $row_rsCategory['catname']; ?> <li><?php echo $row_rsCategory['catname']; ?> <ul> <?php }?> <li><?php echo $row_rsCategory['galleryname']; ?></li> <?php $first = false; } while ($row_rsCategory = mysql_fetch_assoc($rsCategory)); ?> </ul> </li> </ul> I've tried looking for a show/hide script, to toggle category names/gallery names, but could only find ones that have static menu options, and have failed to edit existing code to fit....any help or guidence would be appreciated! Hi there. This is my first thread. I'm completely new to javascript. I want to use dreamweaver with javascript to do a litter project in which I want to move value "Saleman" from drop-menu 1 and value "Billy" from drop-down 2 to a list box. The result should be as follows: dropdown 1 Manager Salesman (to be selected) Cleaner dropdown 2 Billy (to be selected) Susan Ivan --- [Add button] Listbox Salesman - Billy Thank you for your help. Cheers Raymond Hi Everyone! I would genuinely appreciate some help on this one. I'm trying to combine a chained drop down list with the ability for the last selection to show/hide a div. I've researched and found ways to do both individually, but I'm hitting the wall when it comes to combining the javascript. This is how I'd like it to work: -- User selects from DropDown List 1. -- DropDown List 2 options appear based on the selection in 1. -- User selects from DropDown List 2, -- Appropriate div is shown. Here's the Javascript I'm using to show/hide a div: Code: function showDiv(divID) { var div = document.getElementById(divID); div.style.display = ""; //display div } function hideDiv(divID) { var div = document.getElementById(divID); div.style.display = "none"; // hide } function hideAllDivs() { //Loop through the seclect menu values and hide all var courseSelect = document.getElementById("courseSelect"); for (var i=0; i<=courseSelect.options.length -1; i++) { hideDiv(courseSelect.options[i].value); } } function toggle(showID){ hideAllDivs(); // Hide all showDiv(showID); // Show the one we asked for } Here's the Javascript for the chained drop down lists: Code: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> <script type="text/javascript" defer> function cascadeSelect(parent, child){ var childOptions = child.find('option:not(.static)'); child.data('options',childOptions); parent.change(function(){ childOptions.remove(); child .append(child.data('options').filter('.sub_' + this.value)) .change(); }) childOptions.not('.static, .sub_' + parent.val()).remove(); } $(function(){ cascadeForm = $('.cascadeTest'); deptartmentSelect = cascadeForm.find('.deptartmentSelect'); courseSelect = cascadeForm.find('.courseSelect'); cascadeSelect(deptartmentSelect, courseSelect); }); And lastly, my HTML (simplified) Code: <form action="#" class="cascadeTest"> <table> <tr> <th>Organization:</th> <td><select name="deptartmentSelect" class="deptartmentSelect"> <option value="0">Select a Department</option> <option value="1">Dept A</option> <option value="2">Dept B</option> <option value="3">Dept C</option> </select></td> </tr> <tr> <th>Territory:</th> <td><select name="courseSelect" class="courseSelect" onChange="toggle(this.options[this.options.selectedIndex].value)"> <option value="0" class="static">- Courses -</option> <option value="A1" class="sub_1">Course A1</option> <option value="B1" class="sub_2">Course B1</option> <option value="C1" class="sub_3">Course C1</option> </select></td> </tr> </table> </form> <div id="A1" style="display:none;">I am Course A1</div> <div id="B1" style="display:none;">I am Course B1</div> <div id="C1" style="display:none;">I am Course C1</div> Thanks again in advance! I tried implementing a cleaner approach to a web form I had created, but it doesn't seem to be passing the values to the server properly. What gives? This form on the left and right work perfectly, but they have two ridiculously long drop down lists, which would be the "ProgramOfInterest" fields (please use the following values preselected in this form) http://www.nationalcollegesearch.org..._pingpost.html On this form, I tried creating a triple drop down list setup to clean up the older, long lists in this example, but it doesn't pass the values properly. It also seems to not duplicate the new drop down triple drop lists properly as in the original form. You can change the values in the drop downs in the forms to see what I mean. Also just pick Bachelor's > B_Business > Business Administration in the triple drop downs for an example since I don't know how to preselect those values. http://nationalcollegesearch.org/Integrate/PleaseHelpMeWithMyCode/integrate_pingpost_experiment.html Please let me know if there is anything I can do to pass the correct values to the server. Thanks! P.S. Please note that I have disabled the form on the right and intentionally left the action empty. This is the triple drop down script I am using: Code: <script type="text/javascript"> /* Triple Combo Script Credit By Philip M: http://www.codingforums.com/member.php?u=186 Visit http://javascriptkit.com for this and over 400+ other scripts Modified by: jmrker */ var categories = []; categories["startList"] = ["Diploma/Certificate:CE","Associate's:AA","Bachelor's:BA","Master's:MA"]; categories["Diploma/Certificate"] = ["C_Arts & Humanities:CE1","C_Automotive:CE2","C_Computers & IT:CE3","C_Education & Teaching:CE4","C_Health & Medical:CE5","C_Trades & Careers:CE6"]; categories["C_Arts & Humanities"] = ["Desktop Publishing:CEDP","Floral Design:CEFD","General Arts:CEGA","Interior Decorating:CEID","Jewelry:CEJ"]; categories["C_Automotive"] = ["Automotive Technician Training:CAUTO","Collision and Auto Body Repair:CCOLL","Motorcycle Mechanic Training:CMM"]; categories["C_Computers & IT"] = ["Cisco:CECS", "Information Technology:CEIT", "Microsoft:CEMS", "Network Systems:CENSYS", "Oracle:CEOR", "PC Repair:CEPC"]; categories["C_Education & Teaching"] = ["Child Day Ca CEDC", "General Education:CEGE"]; categories["C_Health & Medical"] = ["Dental Assisting:CEDENT", "Fitness:CEFIT", "Healthca CEHC", "Massage Therapy:CMT", "Medical Assisting:CEMEA", "Medical Billing and Insurance Coding:CEMBIC", "Medical Office Administration:CEMOA", "Occupation Therapy:CEOT", "Phlebotomy:CEPHL", "Social Work:CESW"]; categories["C_Trades & Careers"] = ["Administrative Assistant:CEAA", "Animal Ca CEAC", "Appliance Repair:CEAR", "Bookkeeping and Payroll Accounting:CEBOO", "Bridal Consulting:CEBC", "Carpentry and Construction:CECC", "Culinary:CECU", "Drafting:CEDR", "Electronics:CEEL", "Forestry and Wildlife:CEFW", "Gunsmithing:CEGUN", "HVAC:CEHV", "Landscaping:CELS", "Law Enforcement:CELE", " Locksmithing:CELOCK", "Plumbing and Electrical:CEPE", "Private Investigator:CEPI", "Wedding Planner:CEWP"]; categories["Associate's"] = ["A_Arts & Humanities:AA1","A_Business:AA2","A_Criminal Justice:AA3","A_Computers & IT:AA4","A_Education & Teaching:AA5","A_Health & Medical:AA6","A_Science & Technology:AA7","A_Social Sciences:AA8","A_Trades & Careers:AA9"]; categories["A_Arts & Humanities"] = ["Communication:AACOM","Fashion:AAFASH","Game Design:AAGD","General Arts:AAGA","Graphic Design:AAGR","Religion:AAREL","Web Design:AAWD","Writing:AAWR"]; categories["A_Business"] = ["Accounting:AAAC","Administrative Assistant:AAAS","Business Administration:AABA","eBusiness and eCommerece:AAEB","Finance:AAFIN","Human Resources Management:AAHR","International Business:AAIB","Marketing:AAMAR","Organizational Leadership:AAOR","Project Management:AAPM"]; categories["A_Criminal Justice"] = ["Criminal Justice:AACJ","Homeland Security:AAHS","Law:AALAW","Legal Assisting Paralegal:AAPAR","Political Science:AAPS"]; categories["A_Computers & IT"] = ["Computer Networking and Security:AACNS","Computer Science:AACS","Databases:AADB","Information Systems:AAIS","Information Technology:AAIT","Technology Management:AATEM","Web Development:AADEV"]; categories["A_Education & Teaching"] = ["Adult and Higher Education:AAHE","Curriculum and Instruction:AACI","Early Childhood Education:AAEVE","General Education:AAGE","Special Education (K-12):AASE"]; categories["A_Health & Medical"] = ["Gerontology (Study of people as they age):AAGER","Healthca AAHLTH","Healthcare Management:AAHCM","Medical Assisting:AAMA","Medical Billing and Insurance Coding:AAMBIC","Medical Office Administration:AAMOA","Nursing:AANUR","Radiology & Sonography:AARAD"]; categories["A_Science & Technology"] = ["Aviation:AAAV","Engineering Management:AAEN","Environmental Sciences:AAENV","Science:AASCI"]; categories["A_Social Sciences"] = ["Counseling:AACOUN","History:AAHIST","Psychology:AAPSY","Public Administration:AAPA","Public Safety:AAPUBS","Social Science:AASS"]; categories["A_Trades & Careers"] = ["Animal Ca AAAC","Carpentry & Construction:AACAR","Fire and Law Enforcement:AALE","Travel and Tourism:AATR"]; categories["Bachelor's"] = ["B_Arts & Humanities:BA1","B_Business:BA2","B_Computers & IT:BA3","B_Criminal Justice:BA4","B_Education & Teaching:BA5","B_Health & Medical:BA6","B_Science & Technology:BA7","B_Social Sciences:BA9","B_Trades & Careers:BA0"]; categories["B_Arts & Humanities"] = ["Communication:BACOM","Fashion:BAFASH","Game Design:BAGD","General Arts:BAGA","Graphic Design:BAGR","Music:BAMUS","Religion:BAREL","Web Design:BAWD","Writing:BAWR"]; categories["B_Business"] = ["Accounting:BAAC","Business Administration:BABA","eBusiness and eCommerece:BAEB","Entrepreneurial Studies:BAES","Finance:BAFIN","Human Resources Management:BAHR","International Business:BAIB","Marketing:BAMAR","Organizational Leadership:BAOR","Project Management:BAPM"]; categories["B_Computers & IT"] = ["Computer Networking and Security:BACNS","Computer Science:BACS","Databases:BADB","Information Systems:BAIS","Information Technology:BAIT","Technology Management:BATM","Web Development:BADEV"]; categories["B_Criminal Justice"] = ["Criminal Justice:BACJ","Homeland Security:BAHS","Law:BALAW","Legal Assisting Paralegal:BAPAR","Political Science:BAPS"]; categories["B_Education & Teaching"] = ["Adult and Higher Education:BAHE","Curriculum and Instruction:BACI","Early Childhood Education:BAECE","General Education:BAGE","Special Education (K-12):BASE"]; categories["B_Health & Medical"] = ["Gerontology (Study of people as they age):BAGR","Healthca BAHLTH","Healthcare Management:BAHCM","Medical Assisting:BAMA","Nursing:BANUR","Radiology & Sonography:BARAD"]; categories["B_Science & Technology"] = ["Aviation:BAAV","Electronics Engineering:BAEE","Engineering Management:BAEN","Environmental Sciences:BAENV","Mathematics:BAMS","Science:BASCI"]; categories["B_Social Sciences"] = ["Counseling:BACOUN","History:BAHIST","Psychology:BAPSY","Public Administration:BAPA","Public Safety:BAPUBS","Social Science:BASS","Sociology:BASOC"]; categories["B_Trades & Careers"] = ["Fire and Law Enforcement:BALE"] categories["Master's"] = ["M_Arts & Humanities:MA1","M_Business:MA2","M_Computers & IT:MA3","M_Criminal Justice:MA4","M_Education & Teaching:MA5","M_Health & Medical:MA6","M_Science & Technology:MA7","M_Social Sciences:MA9"]; categories["M_Arts & Humanities"] = ["Communication:MACOM","Game Design:MAGD","General Arts:MAGA","Graphic Design:MAGR","Music:MAMUS","Religion:MAREL","Web Design:MAWD","Writing:MAWR"]; categories["M_Business"] = ["Accounting:MAAC","Business Administration:MBA","eBusiness and eCommerece:MAED","Entrepreneurial Studies:MAES","Finance:MAFA","Finacial Planning:MAFPL","Human Resources Management:MAHR","International Business:MAIB","Marketing:MAMAR","Organizational Leadership:MAOR","Project Management:MAPM"]; categories["M_Computers & IT"] = ["Computer Networking and Security:MACNS","Computer Science:MACS","Databases:MADB","Information Systems:MAIS","Information Technology:MAIT","Technology Management:MATM","Web Development:MADEV"]; categories["M_Criminal Justice"] = ["Criminal Justice:MACJ","Homeland Security:MAHS","Law:MALAW","Legal Assisting Paralegal:MAPAR","Political Science:MAPS"]; categories["M_Education & Teaching"] = ["Adult and Higher Education:MAHE","Curriculum and Instruction:MACI","Early Childhood Education:MAECE","General Education:MAGE","Special Education (K-12):MASE"]; categories["M_Health & Medical"] = ["Gerontology (Study of people as they age):MAGR","Healthca MAHLTH","Healthcare Management:MAHCM","Medical Assisting:MAMA","Nursing:MANUR","Radiology & Sonography:MARAD"]; categories["M_Science & Technology"] = ["Aviation:MAAV","Electronics Engineering:MAEE","Engineering Management:MAEN","Environmental Sciences:MAENV","Mathematics:MAMS","Science:MASCI"]; categories["M_Social Sciences"] = ["Counseling:MACOUN","History:MAHIST","Psychology:MAPSY","Public Administration:MAPA","Public Safety:MAPUBS","Social Science:MASS","Sociology:MASOC"]; var nLists = 3; // number of select lists in the set function fillSelect(currCat,currList){ var step = Number(currList.id.replace(/\D/g,"")); for (i=step; i<nLists+1; i++) { document.forms['form1']['List'+i].length = 1; document.forms['form1']['List'+i].selectedIndex = 0; } var tmp = currCat.split(':'); var nCat = categories[tmp[0]]; for (each in nCat) { tmp = nCat[each].split(':'); var nOption = document.createElement('option'); var nData = document.createTextNode(tmp[0]); nOption.setAttribute('value',nCat[each]); nOption.appendChild(nData); currList.appendChild(nOption); } } function getValue(L3, L2, L1) { var l3 = L3.split(':'); var l2 = L2.split(':'); var l1 = L1.split(':'); // alert("Your selection was:- \n" + L1 + "\n" + L2 + "\n" + L3); // alert("Your selection was:- \n" + l1[1] + "\n" + l2[1] + "\n" + l3[1]); } function init() { fillSelect('startList',document.forms['form1']['List1']) } navigator.appName == "Microsoft Internet Explorer" ? attachEvent('onload', init, false) : addEventListener('load', init, false); </script> </head> <body> <form name="form1" action=""> <table> <tr> <td class="frmText" style="color: #000000; font-weight: normal;">Degree:</td> <td><select id='List1' onchange="fillSelect(this.value,this.form['List2'])"> <option selected>Select degree</option> </select> </td> </tr> <tr> <td class="frmText" style="color: #000000; font-weight: normal;">Area of Study:</td> <td><select id='List2' onchange="fillSelect(this.value,this.form['List3'])"> <option selected>Select area of study</option> </select> </td> </tr> <tr> <td class="frmText" style="color: #000000; font-weight: normal;">Program of Interest:</td> <td><select class="frmInput" id="List3" name="ProgramOfInterest" onchange="getValue(this.value,this.form['List2'].value, this.form['List1'].value)"> <option selected >Select program</option> </select> </td> </tr> </table> </form> what can be the reasons for the same code which works perfectly in notepad to not show its result in a jsp application done using eclipse??anything to do with settings? I am not able to display the current date as default in dd/mm/yyyy format in drop down boxes..only dd and yyyy apears but month isnt apearing as default.. can u suggest alternative logic and its code to implement the same?? hi, I am sooo close to getting my project done, I can now output a town name, using Jquery to output mySQL as JSON the only problem I have now... In my code I have [16] which = 'Andover' Is there a way to output my whole array? can I use .each()? if so, where? thanks here is my code 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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Untitled Document</title> <script src="http://code.jquery.com/jquery-1.4.4.js"></script> <script language="javascript" type="text/javascript"> $(document).ready(function () { $.getJSON('json.php', function(data){ $("#content").html(data[16].Town); }); }); </script> </head> <body> <div id="content"></div> </body> </html> http://www.mypubspace.com/dashtest/newjson.html hello I am having a problem to add numbers store in an array. arrayValues[0][0] = 1; arrayValues[0][1] = 2; var col = 0; var sum; for ( var row = 0; row < index; i++ ) sum += arrayValues[col][row]; my result is ==> 12 it is defining my sum variable as string. even I try do do this var sum = 0; to define sum as numeric variable. my result was ==>012. Any idea, this is my first javaScritp code. Thanks. Hi Guys, How do I sum the values of an array and output the result using document.write? Say my array is var number=new Array(1.234,56.43,1.02); THANKS Thought this wud work? Code: <script type="text/javascript"> var x = [1, 2, 3, 4, 5, 6, 7, 8, 9]; document.write(sum(x)); </script> I'm having problems with selecting values from array. I have a dropdown box where you choose what fruit you want to buy. When selected the array should assign 2 values to that fruit. I don't know how to do that. Here's what I have.. I added comments. Javascript part: Code: <script type="text/javascript"> function Fruits() { var selectfruit = newArray( //assigning values to fruit selected from dropdown box newArray("Banana", 1, 1), newArray("Apple", 1.2, 0.5), newArray("Mango", 1.1, 0.9), newArray("Orange", 0.1, 9.99)); var howmanyfruits = Number(document.getElementById("howmanyfruits").value); // how many fruits are you buying var totalfruitsowned = Number(document.getElementById("totalfruitowned").value); // How many fruits do you already have /* cash and coupons needed to buy fruits. cash is cpst for 1 fruit. coupons is cost for 1 fruit cash_all is cost for all fruits you're buying coupons_all is cost for all fruits you're buying each fruits requires cash AND coupons to be bought. Cash and coupons are tied to the first values in Array. Eg. If you choose Apple that value would be 1.2 The 'fruitsmaxtobuy' variable is not tied to the first value, but the second one in array. If you choose Apple that value would be 0.5. */ var cash = Math.round(((totalfruitsowned * 0.51 * selectfruit) + 700)*10)/10; var coupons = Math.round(((totalfruitsowned * 0.51 * selectfruit) + 850)*10)/10; var cash_all = Math.round((howmanyfruits * cash)*10)/10; var coupons_all = Math.round((howmanyfruits * coupons)*10)/10; var fruitsmaxtobuy = Math.round((totalfruitsowned * 0.12 * selectfruit)*10)/10; /* Display Error if nothing is entered or if you forget to enter total fruits */ if (((howmanyfruits=="" || howmanyfruits==null) && (totalfruitsowned=="" || totalfruitsowned==null)) || ((howmanyfruits==Number(document.getElementById("howmanyfruits").value)) && (totalfruitsowned=="" || totalfruitsowned==null))) {document.getElementById("cash").innerHTML = "Error"; document.getElementById("coupons").innerHTML = "Error"; document.getElementById("cash_all").innerHTML = "Error"; document.getElementById("coupons_all").innerHTML = "Error"; document.getElementById("fruitsmaxtobuy").innerHTML ="Error"} else { document.getElementById("cash").innerHTML = cash; document.getElementById("coupons").innerHTML = coupons; document.getElementById("cash_all").innerHTML = cash_all; document.getElementById("coupons_all").innerHTML = coupons_all; document.getElementById("fruitsmaxtobuy").innerHTML =fruitsmaxtobuy} } </script> HTML part: Code: <form action="" id="fruitcost"> <table align="center" width="37.5%" cellpadding="0" cellspacing="0"> <tbody> <tr> <th colspan="2" align="center">Fruit cost calcultor</th> </tr> <tr> <td>Select Fruit:</td> <td align="center"><select id="selectfruit"> <option>Banana</option> <option selected>Apple</option> <option>Mango</option> <option>Orange</option> </select> </td> </tr> <tr> <td>Total Fruits Owned:</td> <td align="center"><input id="totalfruitsowned" type="text" /></td> </tr> <tr> <td>How many fruits are you buying:</td> <td align="center"><input id="howmanyfruits" type="text" /></td> </tr> <tr> <td>Money Needed to buy 1 fruit:</td><td><font id="cash"></font></td> </tr> <tr> <td>Coupons Needed to buy 1 fruit:</td><td><font id="coupons"></font></td> </tr> <tr> <td>Money Needed:</td><td><font id="cash_all"></font></td> </tr> <tr> <td>Coupons Needed:</td><td><font id="coupons_all"></font></td> </tr> <tr> <td>Nr. of fruits you can buy:</td><td><font id="fruitsmaxtobuy"></font></td> </tr> <tr> <td align="center" colspan="2"><input type="button" value="Submit" onclick="Fruits()" /></td> </tr> </tbody> </table> </form> hi, I have this keypressed function: Code: function keyPressed(event, input) { if (event.keyCode == 8) { return true; } var char = event.which ? event.which : event.keyCode; char = String.fromCharCode(char); var exers = "1234 1234 1234"; return (exers.charAt(input.value.length) == char); } This function allow me to press in order the numbers in array (index0). It is works very well. But i want to add an array with more exercises like: Code: var exerc = new Array(); exerc[0]= "1234 1234 1234"; exerc[1] = "5678 5678 5678"; exerc[2] = "9012 9012 9012"; Also, i have a dropdown menu that parser options from a xml file: Code: <form> <select style="width:100px" id='courses'> </select> </form> and my xml file looks like: Code: <courses> <course title="exercise 1"> <lesson>1234 1234 1234</lesson> </course> <course title="exercise 2"> <lesson>5678 5678 5678</lesson> </course> <course title="exercise 3"> <lesson>9012 9012 9012</lesson> </course> . . . </courses> *I write the same index because i have two input field. I see the first choose (depend on dropdown) in first input, and i rewrite the same exercise in the second input. So, it's something like an exercise for me and i stack here. - I repeat. It is work with only one index very well. The problem is that, when i add more that one index in the array. Any suggestion about my problem?Javascript it is not my strong point I try this but it is doesn't work.Baybe it is totally wrong! Code: function keyPressed(event, input) { if (event.keyCode == 8) { return true; } var char = event.which ? event.which : event.keyCode; char = String.fromCharCode(char); var exerc = new Array(); exerc[0]= "1234 1234 1234"; exerc[1] = "5678 5678 5678"; exerc[2] = "9012 9012 9012"; for (i=0;i<exerc.length;i++) { document.getElementById("courses").selectedIndex; } return (exers.charAt(input.value.length) == char); } Hi all I am trying to create a code which stores information about songs The information to be stored are : song ID song name song artist song URL So far what I've done is create an empty array with four properties The code asks the user to enter information and then displays them However i'm having difficulty figuring out how to insert all the information entered in the array. For example if information about 3 songs were entered, how can I insert all of them in the array I created. After storing the information, I want to be able to search for songs by their ID. When I wrote the function to do this, if lets say I entered two songs one with S1 as ID and one with S2 as ID, I type S1 in the search box, but it doesn't return anything. However if I enter S2, it returns the information of the track with this ID, which makes me think that entering information for a second song overwrites the first one This is my code so far: <html> <body> <h1>Tracks and Artists</h1> <script type="text/javascript"> function request(tracks) { for (var i=0;i<2;i++) { tracks.trackID = prompt("Enter track ID") tracks.trackName = prompt("Enter track name") tracks.trackArtist = prompt("Enter artist name") tracks.trackURL = prompt("Enter track URL") alert(display(tracks)) } } function insert() { function display(tracks) { return "Track ID: " + tracks.trackID + "\nTrack name: " + tracks.trackName + "\nTrack artist: " + tracks.trackArtist + "\nTrack URL: " + tracks.trackURL } var tracks = [{trackID: "", trackName:"", trackArtist:"", trackURL:"" }] request(tracks) </script> </body> </html> Hi How can i output two maximum numbers of an array if they are equal? var flower["roses", "violets", "buttercups", "daisies"]; var flowerAmounts[9, 8, 3, 9]; Output should be: The maximum amount of flowers is 9. There are 9 roses and 9 daisies. Hope someone can help, thanks |