Wednesday, August 14, 2019
Monday, November 7, 2011
List Boxes Selection 2
<html>
<head>
<title>List Boxes Selection </title>
</head>
<body>
<script>
var ListUtil = new Object();
function listBoxMani()
{
alert(" listBoxMani() ");
var oListbox = document.getElementById("selAge");
alert(" oListbox "+ ListUtil.getSelectedIndexes(oListbox));
}
ListUtil.getSelectedIndexes = function (oListbox)
{
var arrIndexes = new Array;
for (var i=0; i < oListbox.options.length; i++)
{
if(oListbox.options[i].selected)
{
arrIndexes.push(i);
}
}
return arrIndexes;
};
</script>
<form name="ListBoxes_form1">
<select name="selAge" id="selAge" size="2" multiple="multiple">
<option value="18-21">18-21</option>
<option value="22-25">22-25</option>
<option value="26-29">26-29</option>
<option value="30-35">30-35</option>
<option value="Over 35">Over 35</option>
</select>
<input type="button" value="getSelectedIndex" onClick="listBoxMani();">
</form>
</body>
</html>
Retrieving the selected option(s)
selectedIndex is an attribute of <select> element which contains the index of selected Index, as we previously saw oListbox.selectedIndex
If selection box type is list box ( list box by setting the multiple attribute of the <select/> element to "multiple") ( not for combo box )means it is possible to select more than one option
if multiple options are selected , by using oListbox.selectedIndex we can get only the first selected item , but that really doesn̢۪t help.
What we need is a way to get the index of all the selected options ,to get the index writing an custom method will solve all the problem
For this, you need a custom method, which is the first for the ListUtil object. The getSelectedIndexes() method takes advantage of another special property of the element: the selected property
The HTML DOM defines the selected property as a Boolean value indicating whether the individual option is selected. So, all that is necessary is to loop through the options of a list box and test to see if they are selected or not. If so, you need to save that index into an array that will ultimately hold the indices of all selected options. This method needs only one argument, the list box to check:
The getSelectedIndexes() method can then be used to either retrieve the indexes of the selected
options or, using the length of the returned array, to determine how many options are selected:
var oListbox = document.getElementById("selListbox");
var arrIndexes = ListUtil.getSelectedIndexes(oListbox);
alert("There are " + arrIndexes.length + "option selected." + "The options have the indexes " + arrIndexes + ".");
This code first gets a reference to the list box with the ID "selListbox" and then retrieves the selected indexes and stores them in arrIndexes. The alert displays the a message indicating the number of selected options as well as displaying their indexes (remember, the toString() method of an Array object returns all items in a comma-separated string).
<head>
<title>List Boxes Selection </title>
</head>
<body>
<script>
var ListUtil = new Object();
function listBoxMani()
{
alert(" listBoxMani() ");
var oListbox = document.getElementById("selAge");
alert(" oListbox "+ ListUtil.getSelectedIndexes(oListbox));
}
ListUtil.getSelectedIndexes = function (oListbox)
{
var arrIndexes = new Array;
for (var i=0; i < oListbox.options.length; i++)
{
if(oListbox.options[i].selected)
{
arrIndexes.push(i);
}
}
return arrIndexes;
};
</script>
<form name="ListBoxes_form1">
<select name="selAge" id="selAge" size="2" multiple="multiple">
<option value="18-21">18-21</option>
<option value="22-25">22-25</option>
<option value="26-29">26-29</option>
<option value="30-35">30-35</option>
<option value="Over 35">Over 35</option>
</select>
<input type="button" value="getSelectedIndex" onClick="listBoxMani();">
</form>
</body>
</html>
Retrieving the selected option(s)
selectedIndex is an attribute of <select> element which contains the index of selected Index, as we previously saw oListbox.selectedIndex
If selection box type is list box ( list box by setting the multiple attribute of the <select/> element to "multiple") ( not for combo box )means it is possible to select more than one option
if multiple options are selected , by using oListbox.selectedIndex we can get only the first selected item , but that really doesn̢۪t help.
What we need is a way to get the index of all the selected options ,to get the index writing an custom method will solve all the problem
For this, you need a custom method, which is the first for the ListUtil object. The getSelectedIndexes() method takes advantage of another special property of the element: the selected property
The HTML DOM defines the selected property as a Boolean value indicating whether the individual option is selected. So, all that is necessary is to loop through the options of a list box and test to see if they are selected or not. If so, you need to save that index into an array that will ultimately hold the indices of all selected options. This method needs only one argument, the list box to check:
The getSelectedIndexes() method can then be used to either retrieve the indexes of the selected
options or, using the length of the returned array, to determine how many options are selected:
var oListbox = document.getElementById("selListbox");
var arrIndexes = ListUtil.getSelectedIndexes(oListbox);
alert("There are " + arrIndexes.length + "option selected." + "The options have the indexes " + arrIndexes + ".");
This code first gets a reference to the list box with the ID "selListbox" and then retrieves the selected indexes and stores them in arrIndexes. The alert displays the a message indicating the number of selected options as well as displaying their indexes (remember, the toString() method of an Array object returns all items in a comma-separated string).
List Boxes and Combo Boxes 1
List box and Combo box are created using HTML <select> tag , by default browser renders <select> element as combo box
<html>
<head>
<title>List Boxes and Combo Boxes </title>
</head>
<body>
<script>
function listBoxMani()
{
var oListbox = document.getElementById("selAge");
alert(" oListbox based on Id "+ oListbox.options[oListbox.selectedIndex].getAttribute("value"));
oListbox = document.forms["form1"].selAge;
oListbox = document.forms[0].selAge
}
</script>
<form name="ListBoxes_form1">
<select name="selAge" id="selAge" onchange="listBoxMani();">
<option value="18-21">18-21
<option value="22-25">22-25
<option value="26-29">26-29
o<ption value="30-35">30-35
o<ption value="Over 35">Over 35
</select>
<select name="selAge1" id="selAge1" size="2">
<option value="1">18-21</option>
<option value="2">22-25</option>
<option value="3">26-29</option>
<option value="4">30-35</option>
<option value="5">Over 35</option>
</select>
</form>
</body>
</html>
<select name="selAge" id="selAge" onchange="listBoxMani();">
<option value="18-21">18-21</option>
<option value="22-25">22-25 </option>
<option value="26-29">26-29 </option>
<option value="30-35">30-35 </option>
<option value="Over 35">Over 35 </option>
</select>
Here the above code render an combo box, The value attribute of each is used to determine the value for the control as a whole; the
selected option gives its value to the control (so it can be sent to the server).
<select name="selAge1" id="selAge1" size="2">
<option value="1">18-21</option>
<option value="2">22-25</option>
<option value="3">26-29</option>
<option value="4">30-35</option>
<option value="5">Over 35</option>
</select>
If size (size="2") attributes is added means the above code will be rendered as list box , base on the size attribute items will be visible at the same time , for example the above code render only 2 items at once
Because both controls use the same HTML code, it’s possible to manipulate them using the same
JavaScript code. Naturally, the first step to manipulating either is to get a reference from the document
either by using document.getElementById() or accessing it in the document.forms collection:
oListbox = document.getElementById(“selAge”);
alert(" oListbox based on Id "+ oListbox.options[oListbox.selectedIndex].getAttribute("value"));
oListbox = document.forms[“ListBoxes_form1”].selAge;
oListbox = document.forms[0].selAge;
alert(" oListbox based on Id "+ oListbox.options[oListbox.selectedIndex].getAttribute("value"));
the above code gives the selected value
ps source: Wrox Professional JavaScriptTM for Web Developers
<html>
<head>
<title>List Boxes and Combo Boxes </title>
</head>
<body>
<script>
function listBoxMani()
{
var oListbox = document.getElementById("selAge");
alert(" oListbox based on Id "+ oListbox.options[oListbox.selectedIndex].getAttribute("value"));
oListbox = document.forms["form1"].selAge;
oListbox = document.forms[0].selAge
}
</script>
<form name="ListBoxes_form1">
<select name="selAge" id="selAge" onchange="listBoxMani();">
<option value="18-21">18-21
<option value="22-25">22-25
<option value="26-29">26-29
o<ption value="30-35">30-35
o<ption value="Over 35">Over 35
</select>
<select name="selAge1" id="selAge1" size="2">
<option value="1">18-21</option>
<option value="2">22-25</option>
<option value="3">26-29</option>
<option value="4">30-35</option>
<option value="5">Over 35</option>
</select>
</form>
</body>
</html>
<select name="selAge" id="selAge" onchange="listBoxMani();">
<option value="18-21">18-21</option>
<option value="22-25">22-25 </option>
<option value="26-29">26-29 </option>
<option value="30-35">30-35 </option>
<option value="Over 35">Over 35 </option>
</select>
Here the above code render an combo box, The value attribute of each is used to determine the value for the control as a whole; the
selected option gives its value to the control (so it can be sent to the server).
<select name="selAge1" id="selAge1" size="2">
<option value="1">18-21</option>
<option value="2">22-25</option>
<option value="3">26-29</option>
<option value="4">30-35</option>
<option value="5">Over 35</option>
</select>
If size (size="2") attributes is added means the above code will be rendered as list box , base on the size attribute items will be visible at the same time , for example the above code render only 2 items at once
Because both controls use the same HTML code, it’s possible to manipulate them using the same
JavaScript code. Naturally, the first step to manipulating either is to get a reference from the document
either by using document.getElementById() or accessing it in the document.forms collection:
oListbox = document.getElementById(“selAge”);
alert(" oListbox based on Id "+ oListbox.options[oListbox.selectedIndex].getAttribute("value"));
oListbox = document.forms[“ListBoxes_form1”].selAge;
oListbox = document.forms[0].selAge;
alert(" oListbox based on Id "+ oListbox.options[oListbox.selectedIndex].getAttribute("value"));
the above code gives the selected value
ps source: Wrox Professional JavaScriptTM for Web Developers
Tuesday, May 10, 2011
Drag and Drop
Here is example code for drag and drop
<html>
<head>
<title>Drag and Drop Example </title>
<script type="text/javascript" src="EventUtil.js"> </script>
</head>
<body>
<div id="myDiv1" class="draggable" style="background:red;width:100px;height:100px;position:absolute"></div>
<div id="myDiv2" class="draggable" style="background:blue;width:100px;height:100px;position:absolute;left:100px"> </div> <div id="myDiv3" class="draggable" style="background:green;width:100px;height:100px;position:absolute;left:200px"> </div>
<div id="myDiv4" class="draggable" style="background:yellow;width:100px;height:100px;position:absolute;left:300px"></div>
<script type="text/javascript">
var DragDrop = function(){
var dragging = null;
function handleEvent(event){
//get event and target
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
//alert(" target "+ target);
//determine the type of event
switch(event.type){
case "mousedown":
if (target.className.indexOf("draggable") > -1){
dragging = target;
}
break;
case "mousemove":
if (dragging !== null){
//get event
event = EventUtil.getEvent(event);
//assign location
dragging.style.left = event.clientX + "px";
dragging.style.top = event.clientY + "px";
}
break;
case "mouseup":
dragging = null;
break;
}
};
//public interface
return {
enable: function(){
EventUtil.addHandler(document, "mousedown", handleEvent);
EventUtil.addHandler(document, "mousemove", handleEvent);
EventUtil.addHandler(document, "mouseup", handleEvent);
},
disable: function(){
EventUtil.removeHandler(document, "mousedown", handleEvent);
EventUtil.removeHandler(document, "mousemove", handleEvent);
EventUtil.removeHandler(document, "mouseup", handleEvent);
}
}
}();
DragDrop.enable();
</script>
</body>
</html>
Here at two methods DragDrop:enable() and disable(), is used which provides additional attach and detach all events , and provide addtional measure of control over the dragdrop functionality
here to start DragDrop for an object enable function has to be called , which in turn call EventUtil.addHandler , after which if any move event occurs [mouseup, mousedown,mousemove] in that page means it is captured in handleEvent
In handle event if mousedown is clicked over an div with the class draggable and moved means , X
In this example, an element ’ s left and top coordinates are set equal to the event object ’ s clientX and clientY proper ties, which places the element at the cursor ’ s position in the viewport. The effect is an element that follows the cursor around the page whenever it ’ s moved. that is how DragDrop works
when mouse is released dragging variable is cleared, for implementing DragDrop functionality the object should be in the absolute position
ps: source: Wrox Professional JavaScriptTM for Web Developers
<html>
<head>
<title>Drag and Drop Example </title>
<script type="text/javascript" src="EventUtil.js"> </script>
</head>
<body>
<div id="myDiv1" class="draggable" style="background:red;width:100px;height:100px;position:absolute"></div>
<div id="myDiv2" class="draggable" style="background:blue;width:100px;height:100px;position:absolute;left:100px"> </div> <div id="myDiv3" class="draggable" style="background:green;width:100px;height:100px;position:absolute;left:200px"> </div>
<div id="myDiv4" class="draggable" style="background:yellow;width:100px;height:100px;position:absolute;left:300px"></div>
<script type="text/javascript">
var DragDrop = function(){
var dragging = null;
function handleEvent(event){
//get event and target
event = EventUtil.getEvent(event);
var target = EventUtil.getTarget(event);
//alert(" target "+ target);
//determine the type of event
switch(event.type){
case "mousedown":
if (target.className.indexOf("draggable") > -1){
dragging = target;
}
break;
case "mousemove":
if (dragging !== null){
//get event
event = EventUtil.getEvent(event);
//assign location
dragging.style.left = event.clientX + "px";
dragging.style.top = event.clientY + "px";
}
break;
case "mouseup":
dragging = null;
break;
}
};
//public interface
return {
enable: function(){
EventUtil.addHandler(document, "mousedown", handleEvent);
EventUtil.addHandler(document, "mousemove", handleEvent);
EventUtil.addHandler(document, "mouseup", handleEvent);
},
disable: function(){
EventUtil.removeHandler(document, "mousedown", handleEvent);
EventUtil.removeHandler(document, "mousemove", handleEvent);
EventUtil.removeHandler(document, "mouseup", handleEvent);
}
}
}();
DragDrop.enable();
</script>
</body>
</html>
Here at two methods DragDrop:enable() and disable(), is used which provides additional attach and detach all events , and provide addtional measure of control over the dragdrop functionality
here to start DragDrop for an object enable function has to be called , which in turn call EventUtil.addHandler , after which if any move event occurs [mouseup, mousedown,mousemove] in that page means it is captured in handleEvent
In handle event if mousedown is clicked over an div with the class draggable and moved means , X
In this example, an element ’ s left and top coordinates are set equal to the event object ’ s clientX and clientY proper ties, which places the element at the cursor ’ s position in the viewport. The effect is an element that follows the cursor around the page whenever it ’ s moved. that is how DragDrop works
when mouse is released dragging variable is cleared, for implementing DragDrop functionality the object should be in the absolute position
ps: source: Wrox Professional JavaScriptTM for Web Developers
Events
Events is base for Java script to interact with HTML , Events indicates some type of actions occurs in document or in browser etc,
Dom level 0 Event Handlers
The traditional way of assigning event handlers in Java script is to assign a function to an Event handler property, This was the events handler assignment method introduced in the fourth generation of web browser and still remains in all modern browser due to its simplicity and cross browser support. to assign an event handler to Java script , you must first retrieve a reference to the object to act on , each element has event handler properties the are typically all lowercase , such as onclick , An event handler is assigned by settings the property equal to a function as in this example
<html>
<body>
<div id="myBtn"> Click Here </div>
<script>
var btn = document.getElementById("myBtn");
btn.onclick = function()
{
alert(this.id); //"myBtn"
alert(this.innerHTML);
};
</script>
</body>
</html>
Dom level 2 Event Handler
DOM level 2 Events defines two methods to deal with assignment and removal of Events handlers
addEventListeners() and removeEventListener() . These methods exist on all DOM nodes and accept
three arguments : the event name to handler function and a Boolean value indicating whether to call the event handler during the capture phase (true) or during the bubble phase , Each element has event handler properties that are typically all the lowercase such as onclick, An event handler is assigned by setting the property equal to a function as this example
<html>
<div id="myBtn"> Click Here </div>
<script>
var btn = document.getElementById("myBtn");
btn.addEventListener("click", function()
{
alert(this.id);
}, false);
btn.addEventListener("click", function(){
alert("Hello world!");
}, false);
</script>
</body>
</html>
ps: source: Wrox Professional JavaScriptTM for Web Developers
Dom level 0 Event Handlers
The traditional way of assigning event handlers in Java script is to assign a function to an Event handler property, This was the events handler assignment method introduced in the fourth generation of web browser and still remains in all modern browser due to its simplicity and cross browser support. to assign an event handler to Java script , you must first retrieve a reference to the object to act on , each element has event handler properties the are typically all lowercase , such as onclick , An event handler is assigned by settings the property equal to a function as in this example
<html>
<body>
<div id="myBtn"> Click Here </div>
<script>
var btn = document.getElementById("myBtn");
btn.onclick = function()
{
alert(this.id); //"myBtn"
alert(this.innerHTML);
};
</script>
</body>
</html>
Dom level 2 Event Handler
DOM level 2 Events defines two methods to deal with assignment and removal of Events handlers
addEventListeners() and removeEventListener() . These methods exist on all DOM nodes and accept
three arguments : the event name to handler function and a Boolean value indicating whether to call the event handler during the capture phase (true) or during the bubble phase , Each element has event handler properties that are typically all the lowercase such as onclick, An event handler is assigned by setting the property equal to a function as this example
<html>
<div id="myBtn"> Click Here </div>
<script>
var btn = document.getElementById("myBtn");
btn.addEventListener("click", function()
{
alert(this.id);
}, false);
btn.addEventListener("click", function(){
alert("Hello world!");
}, false);
</script>
</body>
</html>
ps: source: Wrox Professional JavaScriptTM for Web Developers
Thursday, May 5, 2011
Multiple Column Sort
Here i have given the code of Multiple Column Sort
<html>
<head>
<script>
function generateCompareTRs(iCol,sortType)
{
return function compareTRs(oTR1, oTR2)
{
var sValue1 = oTR1.cells[iCol].firstChild.nodeValue;
var sValue2 = oTR2.cells[iCol].firstChild.nodeValue;
if(sortType=='Desc')
{
return -sValue1.localeCompare(sValue2);
}
else
{
return sValue1.localeCompare(sValue2);
}
};
}
function sortTable(sTableID, iCol)
{
var sorttype = document.getElementById('sortTypeHidden').value;
if(sorttype=='Desc')
{
document.getElementById('sortTypeHidden').value='Asce';
}
else
{
document.getElementById('sortTypeHidden').value='Desc';
}
var oTable = document.getElementById(sTableID);
var oTBody = oTable.tBodies[0];
var colDataRows = oTBody.rows;
var aTRs = new Array;
for (var i=0; i <colDataRows.length; i++)
{
aTRs[i] = colDataRows[i];
}
aTRs.sort(generateCompareTRs(iCol,sorttype));
var oFragment = document.createDocumentFragment();
for (var i=0; i <aTRs.length; i++)
{
oFragment.appendChild(aTRs[i]);
}
oTBody.appendChild(oFragment);
}
</script>
</head>
<body>
<input type="hidden" id="sortTypeHidden" name="Asce">
<table border="1" id="tblSort">
<thead>
<tr>
<th onclick="sortTable('tblSort', 0);" style="cursor:pointer">Last Name </th>
<th onclick="sortTable('tblSort', 1);" style="cursor:pointer">First Name </th>
<th onclick="sortTable('tblSort', 2);" style="cursor:pointer">Third < /th>
</tr>
</thead>
<tbody>
<tr>
<td>Smith </td>
<td>John </td>
<td>A Third </td>
</tr>
<tr>
<td>Johnson </td>
<td> Betty </td>
<td>B Third </td>
</tr>
<tr>
<td>Henderson </td>
<td>Nathan < /td>
<td>C Third </td>
</tr>
<tr>
<td>Williams </td>
<td>James </td>
<td>D Third </td>
</tr>
<tr>
<td>Gilliam </td>
<td>Michael </td>
<td>E Third </td>
</tr>
<tr>
<td>Walker </td>
<td>Matthew </td>
<td>F Third </td>
</tr>
</tbody>
</table>
</body>
</html>
How it works
It works as like as Sorting single column Table
Sorting is done by getting the values of the specified column [dom collections] from the table and storing it to an array then sorting the array values.
Now the tr values are sorted using generateCompareTRs() and stored in a array ,
generateCompareTRs() will return another function compareTRs instead of handling it in one function because In general sorting is done using sort () api , which in turn calls another function generateCompareTRs() , in generateCompareTRs compareTRs function added because
compareTRs is a comparison function
an short note about comparison function
A comparison function is a function with a specific algorithm. It’s helpful to take a look at a basic comparison function before continuing with the explanation:
function comparison_function(value1, value2) {
if (value1 < value 2) {
return –1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
};
As you can see, a comparison function compares two values, which is why a comparison function
always has two arguments. If the first argument should come before the second argument, the
function returns –1. If the first argument should come after the second argument, the function
returns 1. If, however, the arguments are equal, the function returns 0. The comparison function
is used in the sort()
As said in desc , comparison function has got only two arguments , but in our case we need two additional argument. The index of the column which is to be sorted and what type of sorting needs to be done(i.e Ascending or Descending Sort ) , so we are constructing a function generateCompareTRs which in turn construct another function compareTRs
And for descending sorting putting a negative sign will do -string1.localeCompare(string2);
Here the sorted values needs to be appended in the table by replacing old tr,
That is done by creating document fragment and adding all the elements (array values) to it
Then appending all child nodes of document fragment back in to the tbody element
ps: source: Wrox Professional JavaScriptTM for Web Developers
<html>
<head>
<script>
function generateCompareTRs(iCol,sortType)
{
return function compareTRs(oTR1, oTR2)
{
var sValue1 = oTR1.cells[iCol].firstChild.nodeValue;
var sValue2 = oTR2.cells[iCol].firstChild.nodeValue;
if(sortType=='Desc')
{
return -sValue1.localeCompare(sValue2);
}
else
{
return sValue1.localeCompare(sValue2);
}
};
}
function sortTable(sTableID, iCol)
{
var sorttype = document.getElementById('sortTypeHidden').value;
if(sorttype=='Desc')
{
document.getElementById('sortTypeHidden').value='Asce';
}
else
{
document.getElementById('sortTypeHidden').value='Desc';
}
var oTable = document.getElementById(sTableID);
var oTBody = oTable.tBodies[0];
var colDataRows = oTBody.rows;
var aTRs = new Array;
for (var i=0; i <colDataRows.length; i++)
{
aTRs[i] = colDataRows[i];
}
aTRs.sort(generateCompareTRs(iCol,sorttype));
var oFragment = document.createDocumentFragment();
for (var i=0; i <aTRs.length; i++)
{
oFragment.appendChild(aTRs[i]);
}
oTBody.appendChild(oFragment);
}
</script>
</head>
<body>
<input type="hidden" id="sortTypeHidden" name="Asce">
<table border="1" id="tblSort">
<thead>
<tr>
<th onclick="sortTable('tblSort', 0);" style="cursor:pointer">Last Name </th>
<th onclick="sortTable('tblSort', 1);" style="cursor:pointer">First Name </th>
<th onclick="sortTable('tblSort', 2);" style="cursor:pointer">Third < /th>
</tr>
</thead>
<tbody>
<tr>
<td>Smith </td>
<td>John </td>
<td>A Third </td>
</tr>
<tr>
<td>Johnson </td>
<td> Betty </td>
<td>B Third </td>
</tr>
<tr>
<td>Henderson </td>
<td>Nathan < /td>
<td>C Third </td>
</tr>
<tr>
<td>Williams </td>
<td>James </td>
<td>D Third </td>
</tr>
<tr>
<td>Gilliam </td>
<td>Michael </td>
<td>E Third </td>
</tr>
<tr>
<td>Walker </td>
<td>Matthew </td>
<td>F Third </td>
</tr>
</tbody>
</table>
</body>
</html>
How it works
It works as like as Sorting single column Table
Sorting is done by getting the values of the specified column [dom collections] from the table and storing it to an array then sorting the array values.
Now the tr values are sorted using generateCompareTRs() and stored in a array ,
generateCompareTRs() will return another function compareTRs instead of handling it in one function because In general sorting is done using sort () api , which in turn calls another function generateCompareTRs() , in generateCompareTRs compareTRs function added because
compareTRs is a comparison function
an short note about comparison function
A comparison function is a function with a specific algorithm. It’s helpful to take a look at a basic comparison function before continuing with the explanation:
function comparison_function(value1, value2) {
if (value1 < value 2) {
return –1;
} else if (value1 > value2) {
return 1;
} else {
return 0;
}
};
As you can see, a comparison function compares two values, which is why a comparison function
always has two arguments. If the first argument should come before the second argument, the
function returns –1. If the first argument should come after the second argument, the function
returns 1. If, however, the arguments are equal, the function returns 0. The comparison function
is used in the sort()
As said in desc , comparison function has got only two arguments , but in our case we need two additional argument. The index of the column which is to be sorted and what type of sorting needs to be done(i.e Ascending or Descending Sort ) , so we are constructing a function generateCompareTRs which in turn construct another function compareTRs
And for descending sorting putting a negative sign will do -string1.localeCompare(string2);
Here the sorted values needs to be appended in the table by replacing old tr,
That is done by creating document fragment and adding all the elements (array values) to it
Then appending all child nodes of document fragment back in to the tbody element
ps: source: Wrox Professional JavaScriptTM for Web Developers
Tuesday, April 26, 2011
Sort Table 1
Here i have given the sample code of how Sort table works
<html>
<head>
<script>
function compareTRs(oTR1, oTR2)
{
var sValue1 = oTR1.cells[0].firstChild.nodeValue;
var sValue2 = oTR2.cells[0].firstChild.nodeValue;
return sValue2.localeCompare(sValue1);
}
function sortTable(sTableID)
{
var oTable = document.getElementById(sTableID);
var oTBody = oTable.tBodies[0];
var colDataRows = oTBody.rows;
var aTRs = new Array;
for (var i=0; i < colDataRows.length; i++)
{
aTRs[i] = colDataRows[i];
}
aTRs.sort(compareTRs);
var oFragment = document.createDocumentFragment();
for(var i=0; i < aTRs.length; i++)
{
oFragment.appendChild(aTRs[i]);
}
oTBody.appendChild(oFragment);
}
</script>
</head>
<table border="1" id="tblSort">
<thead>
<tr>
<th onclick="sortTable('tblSort');" style='cursor:pointer;'> Last Name</th>
</tr>
</thead>
<body>
<tr>
<tdA> Smith</td>
</tr>
<tr>
<tdB> Johnson</td>
</tr>
<tr>
<td> C Henderson</td>
< /tr>
<tr>
<td> DWilliams </td>
</tr>
< tr>
<tdE> E Gilliam </td>
< /tr>
<tr>
<td>F Walker </td>
</tr>
<tr>
<td>Z </td>
</tr>
</tbody>
</table>
</html>
How it works
Sorting is done by getting the values of the column [dom collections] from the table and storing it to an array then sorting the array values.
Now the tr values are sorted and stored in a array ,
Here the sorted values needs to be appended in the table by replacing old tr,
That is done by creating document fragment and adding all the elements (array values) to it
Then appending all child nodes of document fragment back in to the tbody element
ps: source: Wrox Professional JavaScriptTM for Web Developers
<html>
<head>
<script>
function compareTRs(oTR1, oTR2)
{
var sValue1 = oTR1.cells[0].firstChild.nodeValue;
var sValue2 = oTR2.cells[0].firstChild.nodeValue;
return sValue2.localeCompare(sValue1);
}
function sortTable(sTableID)
{
var oTable = document.getElementById(sTableID);
var oTBody = oTable.tBodies[0];
var colDataRows = oTBody.rows;
var aTRs = new Array;
for (var i=0; i < colDataRows.length; i++)
{
aTRs[i] = colDataRows[i];
}
aTRs.sort(compareTRs);
var oFragment = document.createDocumentFragment();
for(var i=0; i < aTRs.length; i++)
{
oFragment.appendChild(aTRs[i]);
}
oTBody.appendChild(oFragment);
}
</script>
</head>
<table border="1" id="tblSort">
<thead>
<tr>
<th onclick="sortTable('tblSort');" style='cursor:pointer;'> Last Name</th>
</tr>
</thead>
<body>
<tr>
<tdA> Smith</td>
</tr>
<tr>
<tdB> Johnson</td>
</tr>
<tr>
<td> C Henderson</td>
< /tr>
<tr>
<td> DWilliams </td>
</tr>
< tr>
<tdE> E Gilliam </td>
< /tr>
<tr>
<td>F Walker </td>
</tr>
<tr>
<td>Z </td>
</tr>
</tbody>
</table>
</html>
How it works
Sorting is done by getting the values of the column [dom collections] from the table and storing it to an array then sorting the array values.
Now the tr values are sorted and stored in a array ,
Here the sorted values needs to be appended in the table by replacing old tr,
That is done by creating document fragment and adding all the elements (array values) to it
Then appending all child nodes of document fragment back in to the tbody element
ps: source: Wrox Professional JavaScriptTM for Web Developers
Subscribe to:
Posts (Atom)
