AZForums: Table rows Reordering - AZForums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Table rows Reordering Javascript

#1 User is offline   Strum Icon

  • AZ Student
  • PipPipPipPipPip
  • View blog
Group:
Members
Posts:
229
Joined:
22-April 06

Posted 07 June 2006 - 04:24 AM

Posted Image

A few months ago I had a couple of people ask me how to reorder a table using nothing but Javascript, and making it user selectable. Someone recently suggested I do a tutorial on it, so here it is, a simple tutorial covering one way of reording a table.

What we will be doing is reording the rows (TR) of our table in alphabetical order, we won't be going into allowing the user to select the order, that is something you can do yourself, it isn't hard :).

Ok, first we need a table to work with, so I created something very simple:

	<html>
	<head>
	<title>Reorder Table</title>
	</head>
	<body>
	
	<table id="mytable" align="center" width="40%" cellpadding="3" cellspacing="0" style="border: 1px solid #000000">
	   <tbody>
		  <tr>
			 <td valign="middle" align="center">C</td>
			 <td valign="middle" align="center">3</td>
		  </tr>
		  <tr>
			 <td valign="middle" align="center">B</td>
			 <td valign="middle" align="center">2</td>
		  </tr>
		  <tr>
			 <td valign="middle" align="center">F</td>
			 <td valign="middle" align="center">6</td>
		  </tr>
		  <tr>
			 <td valign="middle" align="center">A</td>
			 <td valign="middle" align="center">1</td>
		  </tr>
		  <tr>
			 <td valign="middle" align="center">D</td>
			 <td valign="middle" align="center">4</td>
		  </tr>
		  <tr>
			 <td valign="middle" align="center">E</td>
			 <td valign="middle" align="center">5</td>
		  </tr>
	   </tbody>
	</table>
	
	</body>
	</html>


If you notice, you will see that the rows are not in alphabetical order, I purposely mixed them up. Also note the table has been given an id so we can reference it, saves looping through all the tables in the document.

There are many different ways you can go about reording the table, but the easiest way would be to use an array. You could give yourself more work by using a document fragment, but I find that to keep the script short and simple an array works best for what we will be doing. Most of what we will be doing is basic Javascript but throwing in a few DOM methods to remove the rows from the document, and then insert them again. Trust me, if you have good knowledge of Javascript and the DOM, you will see just how easy it is to do.

	<script type="text/javascript">
	<!--
	
	function orderRows(){
	   var rowArray = [];
	   var iRows = document.getElementById("myTable").rows;
	
	   for(r = 0; r < iRows.length; r ++){
		  // Statements
	   }
	}
	
	//-->
	</script>


Explanation Of Above Code - (skip to next part if you are more experienced)

So here is our first bit of code, I haven't posted all the HTML with this, but if you want to do exactly what I am doing, then just place the script inside your <head> tag.

I have created a function called "orderRows" which will be doing all our reording. I used a function because...

1. I have the script in the head part of my document, if I didn't use a function then the code would run straight away. The document reads from top to bottom, so I placed it inside the function so I could call the script when I wanted.

2. By using a function we can then add in options for the user. So for example, maybe we would like to allow the user to reorder them A-Z and also allow them to reorder them Z-A.

Right, carrying on with the script.

On the first line inside our function, we have a variable rowArray that is holding an empty array. I like using square brackets for my arrays, but you can do it the other way...

	var rowArray = new Array();


Next line of our function is a reference to our table, but because we want to grab the rows as well we add the property "rows" to the end.

Next comes our for loop, which has no statements at the moment.


	<script type="text/javascript">
	<!--
	
	function orderRows(){
	   var rowArray = [];
	   var iRows = document.getElementById("mytable").rows;
	
	   for(r = 0; r < iRows.length; r ++){
		  rowArray.push([iRows.item(r).cells.item(0).firstChild.data, iRows.item(r)]);
		  iRows.item(r).parentNode.removeChild(iRows.item(r));
		  r --;
	   }
	
	   rowArray.sort();
	   alert(rowArray);
	}
	
	//-->
	</script>


Our for loop now has 3 lines inside it which I shall explain:

	rowArray.push([iRows.item(r).cells.item(0).firstChild.data, iRows.item(r)]);


To the average coder this may look complicated, but if I break it down, you will see that it is very simple.

	rowArray.push()



"push()" is a method used with arrays to add an item to the end of an array. It is basically the same as...

	rowArray[rowArray.length] = "something"


Now, the reason why we are pushing an item into the array is so that when our loop has finished it will contain our letters from the first cell of each row, and also contain a copy of the row object. Because we want to push more then one item into the array on each iteration, we push a multidimensional array.

	iRows.item(r).cells.item(0).firstChild.data


The first item we want to add into our multidimensional array is the letter from the first cell on each row. To do this we use ".cells.item(0)" to grab the cell (TD). Now, to actually grab the letter, we could have used innerHTML, but in keeping with the DOM I used "firstChild.data". What this does is grabs the first child inside our cell, that being a text node. To grab the value of the text node I used "data", which is exactly the same as "nodeValue" as far as I can tell.

	iRows.item(r)


Next item to go inside our multidimensional array is a copy of the whole row we are currently at in our table. You could use "cloneNode(true)", but I find that putting it directly in works fine.

	rowArray.push([iRows.item(r).cells.item(0).firstChild.data, iRows.item(r)]);


So that line does the building of the array.

	iRows.item(r).parentNode.removeChild(iRows.item(r));
	r --;


Those two lines are rather simple, and if you understand the DOM very well, then the first line you will already understand what it is doing. But, as always, I will explain it just incase.

	iRows.item(r).parentNode.removeChild(iRows.item(r));


That line in english means "child tells parent to be removed".

In coding terms the row we are at in the table needs to be removed from the table, we don't need it anymore as it is placed inside out rowArray array. To remove a row from a table we must grab the parent node (tbody) and tell it to remove the child node we are currently at. We do this so that the table is left empty once then loop has finished.

	r --;


All this is for is so that we don't skip the next row. Because we have removed a row from the table, we would now be considered at the next row, so when the loop iterates it will miss it. So to fix this problem, we deincrement the variable r each time we remove the row from the table.

	rowArray.sort();
	alert(rowArray);


Last two lines of our script are straight forward. Remember that in our array rowArray, we have the letter and row object we grabbed from the table. All we need to do is sort them into alphabetical order, because at the moment our array is in the same order as what they were before we took them from the table.

Note: If you noticed, I placed the letter into the array before the row object. If I didn't, then when it comes to sorting the array, it wouldn't sort how I wanted.

last line is used to alert the whole array to see what we have, used for debugging.



Right, so we now have an empty table and an array that has been ordered in alphabetical order. We now need to add them back into the table. With a little DOM, this is very easy.


	<script type="text/javascript">
	<!--
	
	function orderRows(){
	   var rowArray = [];
	   var iRows = document.getElementById("mytable").rows;
	
	   for(r = 0; r < iRows.length; r ++){
		  rowArray.push([iRows.item(r).cells.item(0).firstChild.data, iRows.item(r)]);
		  iRows.item(r).parentNode.removeChild(iRows.item(r));
		  r --;
	   }
	
	   rowArray.sort();
	
	   var iTbody = document.getElementById("mytable").firstChild;
	
	   for(o = 0; o < rowArray.length; o ++){
		  iTbody.appendChild(rowArray[o][1]);
	   }
	}
	
	//-->
	</script>


Now, to place the rows back into our table we store a reference to the tbody inside our table in the variable iTbody. We use "firstChild" to grab the first child of the table, that being the "tbody" element.

Next comes our for loop which loops through our rowArray array. To insert the row back into the table, we just use "appendChild()" and pass the second bit of data of our multidimensional as the parameter, that being the row object.

To run your code, place an "onload" event handler in the body tag.

	<body onload="orderRows()">


When ran, you will see the table reorded into an alphabetical order.

With a little bit of changing, you can allow the user to order the rows A-Z and Z-A.

This post has been edited by Strum: 15 June 2006 - 06:57 AM

RedLine Media™
Anizone Gift : [X] | [X]
MOTW #2 Winner [X]

Love Mozilla : Posted Image
0

#2 User is offline   Rokan Icon

  • AZ Guru
  • PipPipPipPipPipPipPipPipPipPip
  • View blog
Group:
+ Legendary
Posts:
6,657
Joined:
29-August 05

Posted 07 June 2006 - 08:35 AM

Another Great Tutorial Strum. I'll move this along with your others to the web tutorials forum.

Thank you for submitting it :)
0

#3 User is offline   Strum Icon

  • AZ Student
  • PipPipPipPipPip
  • View blog
Group:
Members
Posts:
229
Joined:
22-April 06

Posted 07 June 2006 - 11:31 AM

hehe np man ... hope i'll help someppl with all those tuts :)
RedLine Media™
Anizone Gift : [X] | [X]
MOTW #2 Winner [X]

Love Mozilla : Posted Image
0

#4 User is offline   Marissa. Icon

  • .Style your Dreams.
  • PipPipPipPipPipPipPip
  • View blog
Group:
Members
Posts:
965
Joined:
29-August 05

Posted 07 June 2006 - 05:09 PM

That is an extremely clever code. Well done Strum :P


.: AZ Dedicated Member :.
Join in with my debates and learn something new.
.xStyleyourDreamsx.
0

#5 User is offline   Strum Icon

  • AZ Student
  • PipPipPipPipPip
  • View blog
Group:
Members
Posts:
229
Joined:
22-April 06

Posted 07 June 2006 - 05:44 PM

I think im gonna keep some coding tuts for later cuz i've posted like 15 in 2 days lol ... I'll work on a Web Tutorials on how to make a portfolio or clan site ... whatever :) thx for comments.
RedLine Media™
Anizone Gift : [X] | [X]
MOTW #2 Winner [X]

Love Mozilla : Posted Image
0

#6 User is offline   Oosband Icon

  • DnB Oos
  • PipPipPipPipPipPipPipPipPipPip
  • View blog
Group:
+ Legendary
Posts:
5,527
Joined:
30-August 05
Location:
UK

Posted 07 June 2006 - 06:34 PM

Wow! Is there anything you cant do?!?
How good are you with PHP?
0

#7 User is offline   Strum Icon

  • AZ Student
  • PipPipPipPipPip
  • View blog
Group:
Members
Posts:
229
Joined:
22-April 06

Posted 07 June 2006 - 09:05 PM

Well to be unest with ya OosBand , there's always something new* to learn in this domaine so i can do a lot but im still learning and mostly about cgi ... and i'll able to make it soon mouahahahaha lol :)

This post has been edited by Strum: 07 June 2006 - 09:06 PM

RedLine Media™
Anizone Gift : [X] | [X]
MOTW #2 Winner [X]

Love Mozilla : Posted Image
0

#8 User is offline   Oosband Icon

  • DnB Oos
  • PipPipPipPipPipPipPipPipPipPip
  • View blog
Group:
+ Legendary
Posts:
5,527
Joined:
30-August 05
Location:
UK

Posted 07 June 2006 - 09:25 PM

PHP is much better than JS or CGI, barely anyone uses those two anymore...
0

#9 User is offline   Strum Icon

  • AZ Student
  • PipPipPipPipPip
  • View blog
Group:
Members
Posts:
229
Joined:
22-April 06

Posted 08 June 2006 - 09:37 PM

OosBand ... you might be crazy cuz in PHP you got HTML parts right ? right ! and some ppl add Java to make something that HTML can't do and i dont know what your saying about php is better than ... cuz each files , can be php , tpl , css or cgi make different operation. Thats it !

An example ... the site based on Steam Network that Greyfox made. In the coding , he added a Javascript "window.close();" into his site page , so when you click it , it make close the window ...
RedLine Media™
Anizone Gift : [X] | [X]
MOTW #2 Winner [X]

Love Mozilla : Posted Image
0

#10 User is offline   Oosband Icon

  • DnB Oos
  • PipPipPipPipPipPipPipPipPipPip
  • View blog
Group:
+ Legendary
Posts:
5,527
Joined:
30-August 05
Location:
UK

Posted 08 June 2006 - 10:00 PM

I get where you're comming from, but in this current age, PHP in the in code...if you want to make it big in coding, you need to know php like the back of your hand.
0

#11 User is offline   Strum Icon

  • AZ Student
  • PipPipPipPipPip
  • View blog
Group:
Members
Posts:
229
Joined:
22-April 06

Posted 08 June 2006 - 10:09 PM

yeah thats true but java will always stay ... for cgi dont matter lol :)
RedLine Media™
Anizone Gift : [X] | [X]
MOTW #2 Winner [X]

Love Mozilla : Posted Image
0

#12 User is offline   Doomed Icon

  • Behind the Curtain
  • PipPipPipPipPipPipPipPipPip
  • View blog
Group:
Members
Posts:
3,031
Joined:
07-November 05

Posted 08 June 2006 - 10:15 PM

Oos i think you're crazy. The possibilities with CGI are almost limitless.
Dark Voltage already came.
Thanks to W.B. Yates for the sig.
Posted Image
0

#13 User is offline   Strum Icon

  • AZ Student
  • PipPipPipPipPip
  • View blog
Group:
Members
Posts:
229
Joined:
22-April 06

Posted 09 June 2006 - 01:51 AM

cgi need php , html or other files type to work so
RedLine Media™
Anizone Gift : [X] | [X]
MOTW #2 Winner [X]

Love Mozilla : Posted Image
0

#14 User is offline   devcline Icon

  • AZ Beginner
  • PipPip
  • View blog
Group:
Members
Posts:
21
Joined:
11-November 08

Posted 11 November 2008 - 03:38 PM

i really like your way of coding :) really great ! . I can reoder Rows on reflesh on manualy?
0

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users