JavaScript - Sorting An Array Of Records By Value Of Field In Records
Hi,
I have written this program: Code: var scores=[]; function sortScores(scoreRecs){ for(i=0;i<scoreRecs.length;i++) scores.push(scoreRecs[i]); for(var i=0;i<scores.length;i++) { for(var j=i+1;j<scores.length;j++) { if(Number(scores[i])>Number(scores[j])) { tempValue=scores[j]; scores[j]=scores[i]; scores[i]=tempValue; } } } alert(scores); } sortScores(["5","6","5","7","7"]); to take an array of variables in calling the function (ie sortScores), place these variables into an empty array("scores"), apply the bubble sort to scores, and then alert scores in sorted form. When I use test values like I have above, where they are all just numbers, this program works perfectly and alerts the "scores" array, correctly sorted. However, what I would like to do is to call the function with an array of records, each containing two fields, and apply the same sort to the array of records, based on the value in the first field of each record.To illustrate, i'd like to be able to call the function thus: Code: sortScores([{sco 0,index:0},{sco 2, index:1},{sco 1,index:2}]); and for it to sort the records in descending order of the value of the "score" field. So the above call would alert: Code: [{sco 2,index:1},{sco 1,index:2},{sco 0,index:0}] however, i'm not sure how i'd reference the numeric part of the f1 of each record in the sort? Hopefully you can see what I'm trying to achieve...any ideas would be greatly appreciated. Similar Tutorials<!-- *** NEED HELP PASSING VALUE id TO POPULATE SUBRECORDS *** --> <!-- *** See line #51 to #55 *** --> <?php session_start(); ob_start(); if($_SESSION[userdetails]->role != "Admin") { die("Access Denied!"); } require_once("includes/connect.php"); // Check if he has the right info. $sql = sprintf("SELECT * FROM members ORDER BY username ASC", $_SESSION[userdetails]->id); $query = mysql_query($sql); // You are now connected ?> <head> <html> <head> <title>Split ListBox Text To Text Boxes</title> <script type="text/javascript"> <!-- archaic format: language="javascript" --> function SplitText (info) { if (info == '') { return; } var tarr = info.split(","); document.getElementById('tBox1').value = tarr[0]; document.getElementById('tBox2').value = tarr[1]; document.getElementById('tBox3').value = tarr[2]; document.getElementById('tBox4').value = tarr[3]; } </script> </head> <body> <form name="convert"> <p style="margin: 2px"> <p><select name="Groups" style="width: 176; height: 19; border: 1px solid #C0C0C0 ; font-size: 11px; font-family:Arial" size="1" onChange="SplitText(this.value)"> <option>===Select Group===</option> <?php $sql1 = mysql_query("SELECT * FROM qw_groups"); while($r1=mysql_fetch_assoc($sql1)){ $f1 = $r1[id]; $f2 = $r1[GroupName]; echo "<option value='$f1,$f2,,'>$f2</option>"; } echo "</select>"; ?> <p><select name="GroupItems" style="width: 176; height: 19; border: 1px solid #C0C0C0 ; font-size: 11px; font-family:Arial" size="1" onChange="SplitText(this.value)"> <option>===Select Group Item===</option> <?php // **** IS IT POSSIBLE TO PASS THE VALUE "$f1" FROM GROUPS TO GROUPITEMS **** // **** I WANT TO POPULATE THE SECOND DROPDOWN LIST WITH SUB-RECORDS WITHOUT SUBMIT /POST /REFRESH /OR RELOAD **** // WHERE id = $f1 ?? maybe some java code id = $val onChange ?? $sql2 = mysql_query("SELECT * FROM qw_groupitems WHERE id = $f1"); while($r2=mysql_fetch_assoc($sql2)){ $f3 = $r2[Subid]; $f4 = $r2[GroupItem]; echo "<option value='$f1,$f2,$f3,$f4'>$f4</option>"; } echo "</select>"; ?> </p> <!-- Input selected data from listBox --> <p style="margin: 2px"> <input type="text" name="textbox1" id="tBox1" value=""><br> <input type="text" name="textbox2" id="tBox2" value=""><br> <input type="text" name="textbox3" id="tBox3" value=""><br> <input type="text" name="textbox4" id="tBox4" value=""><br> </p> </form> </body> </html> I already have something that paginates thru records by clicking a next or back link that works great. Now I would like to upgrade this to a paginate script that does not do page loads everytime the user clicks next or back. I know how to refresh the new record into input fields with ajax so I don't need help there but how do I change the text of the record count that displays to the user on the screen with javascript as the page will not refresh so I can't write "Record 5 of 200" or whatever record the user is on. I guess I'm asking how can I write to the screen without page refreshes. I will be using an onclick event to click thru the records. How can I add a different number as a parameter to the onclick event everytime I click it without page refreshes? I was going to use the record id number as a parameter to the function so I know what record to get. Sorry for the long rambling post. Tracy I encountered an error when my table had only one or zero records when using the filtertable library from javascriptkit.com Here is the solution to fixing it for anyone else who encountered it. Perhaps the library could be updated with the fix? The error is in the function getChildElms() when the variable 'n' is undefined. Working backwards, I found that there was a problem with some logic in the setFilterGrid() function where the value of 'ref_row' is changed if undefined to a value of '2'. In fact, that value is needed in the line to set the value of tbl.tf_ref_row, but accidentally caused a problem in the call to getCellsNb() where at some point it tries to get at row 2 (offset 3) which doesn't exist in my case. I fixed it by creating a new variable and leaving it as 'undefined' unless ref_row contained a number (passed into the function). This is a section of the function with the fix: Code: var _row; if(ref_row == undefined){ ref_row=2; } else { ref_row=(ref_row+2); _row = ref_row; } var ncells = getCellsNb(id,_row); tbl.tf_ncells = ncells; if(tbl.tf_ref_row==undefined) tbl.tf_ref_row = ref_row; tbl.tf_Obj = fObj; if( !hasGrid(id) ) AddGrid(id); However, if you have zero rows, you still get an error since there are no tr elements. I fixed this by having the code use the th elements instead when zero tr elements are found. This code is in the function 'getCellsNb()' below: Code: { var t = grabEBI(id); var tr; if(nrow == undefined){ tr = grabTag(t,"tr")[0]; } else { tr = grabTag(t,"tr")[nrow]; } var n = getChildElms(tr); if (!n){ n = getChildElms(th); // Check for 'th' elements instead. return n.childNodes.length; } return n.childNodes.length; } If you have no data rows and no header row, then you're on your own :) Hello I'm using the combo box selection menu by Elviro Mirko from this site (http://www.javascriptkit.com/script/...plecombo.shtml) I have made amendments to show my own data, however what I would like to happen is if the user selects from the top combo only, then all the records would be shown, whereas selecting from the second combo merely 'drills down' and shows the records required. - Hope that makes sense. The code is as follows: Code: // first combo box data_1 = new Option("Douglas - DIS", "$"); data_2 = new Option("Douglas - COE", "$$"); data_3 = new Option("Peel - DIS", "$$$"); data_4 = new Option("Peel - COE", "$$$$"); data_5 = new Option("Ramsey - DIS", "$$$$$"); data_6 = new Option("Ramsey - COE", "$$$$$$"); data_7 = new Option("Castletown - DIS", "$$$$$$$"); data_8 = new Option("Castletown - COE", "$$$$$$$$"); // second combo box data_1_1 = new Option("Registry Office Douglas", "-"); data_1_2 = new Option("Broadway Baptist Church Douglas", "-"); data_1_3 = new Option("Finch Hill Congregational Church Douglas", "-"); data_2_1 = new Option("St Thomas's Church", "--"); data_2_2 = new Option("St Barnabas Church", "--"); data_2_3 = new Option("St George's Church", "--"); The HTML code is as follows: Code: <select name="combo0" id="combo_0" onChange="change(this);" style="width:200px;"> <option value="">Select a Register...</option> <option value="Douglas - DIS">Douglas - DIS</option> <option value="Douglas - COE">Douglas - COE</option> <option value="Peel - DIS">Peel - DIS</option> <option value="Peel - COE">Peel - COE</option> <option value="Ramsey - DIS">Ramsey - DIS</option> <option value="Ramsey - COE">Ramsey - COE</option> <option value="Castletown - DIS">Castletown - DIS</option> <option value="Castletown - COE">Castletown - COE</option> </select> <BR><BR> <select name="combo1" id="combo_1" onChange="change(this)" style="width:200px;"> <option value="">Select a venue...</option> </select> the link for the actual site is http://www.manxbmd.com/cgi-bin/db.cg...m;db=marriages If you choose Douglas-COE and search, then 0 records are found, if you choose Douglas-COE followed by St Thomas's then still 0 records are found but if you search the surname Allitson you'll see that there is a record there. I'm not sure where I've gone wrong - I'm completely new to Javascript. Any suggestions welcomed. regards Pendle Ignore post (if mod, please delete)
I am trying to make an addition to a .js plugin for a wiki. Currently it does not support sorting my IP address. So far I have created the below code which does more than the script initially did, but is still not sorting 100% correctly. Any tips? Code: sort_ipaddr: function(a,b){ aa = a[0].split(".",4); bb = b[0].split(".",4); var counti = 0; for (var i=0; i<4; i++) { if (parseInt(parseFloat(aa[i])) == parseInt(parseFloat(bb[i]))){} if (parseInt(parseFloat(aa[i])) < parseInt(parseFloat(bb[i]))){counti--} if (parseInt(parseFloat(aa[i])) > parseInt(parseFloat(bb[i]))){counti++} } return counti; }, EDIT I've also tried this which is closer but still not there. Code: sort_ipaddr: function(a,b){ aa = a[0].split(".",4); bb = b[0].split(".",4); var resulta = (aa[3]+(aa[2]*256)+(aa[1]*256*256)+(aa[0]*256*256*256)); var resultb = (bb[3]+(bb[2]*256)+(bb[1]*256*256)+(bb[0]*256*256*256)); return resulta-resultb; }, This results in a list like so: 10.1.15.22 10.1.16.22 10.1.15.23 10.1.15.24 10.1.16.24 10.1.15.25 So, I'm using code like the following and getting errors: result = a list of cars with each property separated by ',' and each car separated by '|' This code creates and populates the array (seems to work) Code: var carList = new Array(); var cars = new Array(); var properties = new Array(); cars = result.split("|"); for(var i=0; i<cars.length;i++){ properties = cars[i].split(","); carlist[carlist.length++] = new car(items[0],items[1],items[2]); function car(id,make,model){ carID = id; carMake = make; carModel = model; } Later, I want to sort the array and call it like this: carList.sort(carSort); here's the sort code Code: function carSort(a, b){ var x = a.carMake.toLowerCase(); var y = b.carMake.toLowerCase(); return ((x < y) ? -1 : ((x > y) ? 1 : 0)); } I get the error that "a.carMake does not exist" (in firebug). What am I doing wrong? I am trying to sort an array of strings based on the location of a string called "this.oText.value" inside an array of strings called "aList." If "this.oText.value" comes earlier in an entry in aList (call it "a") than another entry "b", I want "a" to appear before "b". Clearly, there is something very wrong with my code. It really isn't doing anything as of right now. Code: aList.sort(sortArray); function sortArray(a,b) { if(a.toLowerCase().indexOf(this.oText.value.toLowerCase()) < b.toLowerCase().indexOf(this.oText.value.toLowerCase())) return 1; else if(a.toLowerCase().indexOf(this.oText.value.toLowerCase()) > b.toLowerCase().indexOf(this.oText.value.toLowerCase())) return -1; else return 0; } What I need help with is sorting the [0] of my array. I need it to sort so that if the user puts in his last name, whether its uppercase or lowercase (Adams, adams), it will sort through the list of students I add, and put them in an alphabetic order i.e adams, Adams, cook, Douglas....and so on. Here is the code that I have below for just sorting by last name, which will seperate the lowercase entries from the uppercase entries. That would be the opposite of what I want. I had it sorted so that it would sort the [o], which is where the last name value is located. Any thoughtful help would be appreciated. Code: function Last_names( s1, s2 ) { if ( s1[0] > s2[0] ) return 1; return 0; } function sortLast(form) { StudentsLists.sort( Last_names ); windows(form);//calling the windows function each time the sortLast function is called } Code: var myarray2=[25, 8, 7, 41]; myarray2.sort(function(a,b){return a - b}) I have tried this code and it works. What I don't understand is, how does array understand which value should be taken as "a" and "b" ? How does javascript understand what is to be done with values, if it is not specified by coding logic ? Is there some kind of in-built functionality ? How is that functionality triggered ? Do I not require further coding as Code: for(i=0; i<myarray2.length; i++){ j=i+1; for((myarray2[i]-myarray2[j])>0){ var a = myarray2[i]; myarray2[i] = myarray2[i+1]; myarray2[i+1] = a; j=j+1;} } and then run two loops for two comparing two values ? Thanks Hi All. I have a dynamic Coldfusion form which adds multiple addresses which holds fields like Town, Postcode, ResidentFromDate, ResidentToDate... and on click of the save button I have a script function that runs which I am trying add all the elements of this form into an array and then sort by ResidentFromDate and output the results... Here is what I have at the minute but my sort does not seem to be working and is throwing out results in the following order (10/2006, 01/2005, 08/2006, 01/2007) and that is clearing not in descending order... If someone could take a look at my script and tell me what is wrong I would be much appreciated (see below) * I seem to be getting results and it is just not sorting correctly, so my theory is something is up with the part where I am calling addresses.sort. Code: var dates = { convert:function(d) { // Converts the date in d to a date-object. The input can be: // a date object: returned without modification // an array : Interpreted as [year,month,day]. NOTE: month is 0-11. // a number : Interpreted as number of milliseconds // since 1 Jan 1970 (a timestamp) // a string : Any format supported by the javascript engine, like // "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc. // an object : Interpreted as an object with year, month and date // attributes. **NOTE** month is 0-11. return ( d.constructor === Date ? d : d.constructor === Array ? new Date(d[0],d[1],d[2]) : d.constructor === Number ? new Date(d) : d.constructor === String ? new Date(d) : typeof d === "object" ? new Date(d.year,d.month,d.date) : NaN ); }, compa function(a,b) { // Compare two dates (could be of any type supported by the convert // function above) and returns: // -1 : if a < b // 0 : if a = b // 1 : if a > b // NaN : if a or b is an illegal date // NOTE: The code inside isFinite does an assignment (=). return ( isFinite(a=this.convert(a).valueOf()) && isFinite(b=this.convert(b).valueOf()) ? (a>b)-(a<b) : NaN ); }, inRange:function(d,start,end) { // Checks if date in d is between dates in start and end. // Returns a boolean or NaN: // true : if d is between start and end (inclusive) // false : if d is before start or after end // NaN : if one or more of the dates is illegal. // NOTE: The code inside isFinite does an assignment (=). return ( isFinite(d=this.convert(d).valueOf()) && isFinite(start=this.convert(start).valueOf()) && isFinite(end=this.convert(end).valueOf()) ? start <= d && d <= end : NaN ); } } // define array var addresses = []; // if atAddrSince is greater than 5 years from today if (atAddrSince > addrFromValidate) { // loop round each previous address for (i=1;i<=maxID;i++) { var addrPart = []; if (eval('document.fmAddPrevAddr.address1'+i)) { var address1 = eval('document.fmAddPrevAddr.address1'+i+'.value'); var town = eval('document.fmAddPrevAddr.town'+i+'.value'); var country = eval('document.fmAddPrevAddr.country'+i+'.value'); var postcode = eval('document.fmAddPrevAddr.postcode'+i+'.value'); var residentfrom = eval('document.fmAddPrevAddr.ataddrsince'+i+'.value'); var residentto = eval('document.fmAddPrevAddr.ataddrto'+i+'.value'); // insert into array addrPart[0]=address1; addrPart[1]=town; addrPart[2]=country; addrPart[3]=postcode; addrPart[4]=residentfromdate; addrPart[5]=residenttodate; addresses.push(addrPart); } } addresses.sort(sortfunction) function sortfunction(a, b) { if(dates.compare(a[4],b[4]) == -1) { return true; } else { return false; } } for (var v=0;v<addresses.length;v++) { var addresses1 = addresses[v]; alert(addresses1[4]); } } Many Thanks, George Hi everyone I'm having a hard time, wrapping my head around an array sort+combine function. I have an array which would look somewhat (these are simplified numbers) like this Code: TestArray = [ ["222222","1"], ["222222","1"], ["222222","1"], ["333333","1"] ["111111","1"], ["000000","2"], ["111111","2"], ["111111","2"], ["222222","20"], ]; I got it as far as to be sorted like this: Code: SortedArray = [ ["000000","2"], ["111111","1"], ["111111","2"], ["111111","2"], ["222222","1"], ["222222","1"], ["222222","20"], ["222222","1"], ["333333","1"] ]; And from there to this: Code: BadlyMergedArray = [ ["000000","2"], ["111111,"1","2"], ["222222","1","20","1"], ["333333","1"] ]; But I want to end up with this: Code: MergedArray = [ ["000000","2"], ["111111","1","2"], ["222222","1","20"], ["333333","1"] ]; So the first part of the inner arrays is the first item to be sorted and combined by. After that, the smaller numbers have to do practically the same, while staying in the correct order under the first sort. I'm only a spare time programmer, and my code is probably one of the most confusing pieces of code ever written. I am assuming that this is some fairly easy stuff for one of you guys. I can post my code, but I think there's a much easier solution to it, so I wanted to see if someone can point me in the right direction, or show me how this is properly done. Thanks so much! here's to hoping! patrick/shootingpandas I have a form which has various fields which are arrays (so the name of a field may be myField[]). The reason for this is that the form has add buttons to add another field or fields for the purpose of entering another email address, etc., to send invitations and do other things. The problem that I am running into is how to access the individual fields in an array of fields inside javascript to do form validation. So if I have an email address field name emailAddress[], and using the add button, the user of my site adds 3 other copies of the emailAddress[] field, I want to then do form validation onSubmit to ensure those email address are valid using standard procedures. However, inside the javascript code, how do I access the individual fields that make up emailAddress[]? I just cannot find anywhere online the proper way to get at these values. If anyone can help me, I would greatly appreciate it. Happy Holidays [ICODE] <html> <head> <title>ABS</title> <?php $j="dove"; ?> <script language="JavaScript" type="text/javascript"> <!-- function checkform ( form ) { if (form.Name.value == "") { alert( "Please enter your email address." ); form.Game.value="<?php echo $j;?>"; form.Name.focus(); return false ; } if (form.Game.value == "") { alert( "Please enter your game address." ); form.Game.focus(); return false ; } if (document.form.Shame[0].value== "") { alert( "Please enter your game address." ); form.Game.focus(); return false ; } return true ; } </script> </head> <body> <form name="form" action="Store_it.php" method="post" onSubmit="return checkform(this);"> <input type="text" name="Name" /> <input type="text" name="Game" /> <input type="text" name="Shame[]" /> <input type="text" name="Shame[]" /> <input type="text" name="Shame[]" /> <input name="submit" type="submit"> </form> </body> </html> [icode] I need to use the array's shame and just check if the third one is not empty. I have searched DOM and other stuff but i cannot get to the 2 element of the array shame. How do i check the value of the array. Hi, I'm struggling with all this DOM stuff so I hope someone can help. I have a form with multiple input fields and I'm trying to identify the specific input field that is in focus so that I can display a relevant status bar message. I have a message array with various entries in it and I'm calling a showStatus() function with an onfocus function from the form itself e.g. The code in the input form = Code: <input type="text" name="first" size="31" maxlength="20" class="entry" onfocus="showStatus()"/> The showStatus() function so far is = Code: function showStatus() { var message = ['Please provide your First Name.', plus loads of other properley formatted status messages......] var x=document.getElementById().focus(); window.status = message[x]; } I'd like to access the array variable of the item that is in focus not only for the message but also for an onblur function to validate input. Any ideas? My thanks R hiiii, im new to javascripts . Can anyone help me to know that a javascript which is validating a phone number accepts only digits but if the text field is left empty it should accept the entry as an empty entry.... plz share knowledge u will be more knowledgeable Hi folks. Looking to see if anyone could tell me where I'm going wrong with this script... I'm trying to have a field automatically filled with the day of the week ("Monday", "Tuesday", "Wednesday" and so on), upon the user selecting a date from the datepicker jQuery. If this isn't clear, I'll clarify further down the page. Here is the script: Code: <script type="text/javascript"> jQuery(document).ready(function($){ $('input[name="item_meta[428]"]').change(function(){ var d = $('input[name="item_meta[428]"]').val(); var n = new Date(d).getDay(); if(n == 0) val v = 'Sunday'; else if(n == 1) val v = 'Monday'; else if(n == 2) val v = 'Tuesday'; else if(n == 3) val v = 'Wednesday'; else if(n == 4) val v = 'Thursday'; else if(n == 5) val v = 'Friday'; else if(n == 6) val v = 'Saturday'; $('input[name="item_meta[429]"]').val(v).change(); }); }); </script> I'm basically trying to say, if the user selected today (15/05/2012) in the field 428 it would fill the field 429 with "Tuesday". Again, if the user selected 18/05/2012 in the field 428 then it would automatically fill field 429 with "Friday". It's being done to work in conjunction with a wordpress plugin called Formidable Pro hence the item_meta[428] etc. Any assistance would be greatly appreciated. Sam. I have a text field, call it income, that when the input is > 0 I need to dynamically show the next text box, and if it is blank hide the next text box. I would like to use onBlur but can't seem to get it to work. Can I do this? Help Hi Experts, I have designed an online registration system for a non profit in ASP/SQL. After the members register for classes they are automatically redirected to an invoice page with class fees. At the bottom of the page I have a Total Fees field of all the classes. The member is supposed to pay this amount to our organization. Question: We decided to do an online payment this year and would like to calculate a 2% additional amount on the Total Fees. This amount is paid to the Payment Merchant site. We cannot afford to lose the 2% since we are a non profit. Would really appreciate if someone can tell me how to 1) Add a new field under the Total field 2) And calculate the 2% additional fees and do a Grand Total. Thanks in advance. I have two drop down fields. When I select any value in the first drop down i want the second dropdown to automatically populate the value related to the first one. For e.g i have the first field as name and the second field as measured in. If I select 'Potato' in the first dropdown then the second drop down should populate 'kg'. Please help.
|