JavaScript DHTML/HTML/Table

Материал из Web эксперт
Перейти к: навигация, поиск

Accessing userProfile Data

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>userProfile Object</TITLE> <SCRIPT LANGUAGE="JavaScript"> var attrs = ["Business.City","Business.Country","Business.Fax",

            "Business.Phone","Business.State","Business.StreetAddress",
            "Business.URL","Business.Zipcode","Cellular","Company",
            "Department","DisplayName","Email","FirstName",
            "Gender","Home.City","Home.Country","Home.Fax",
            "Home.Phone","Home.State","Home.StreetAddress",
            "Home.Zipcode","Homepage","JobTitle","LastName",
            "MiddleName","Notes","Office","Pager"]

function loadTable() {

   // make sure this executes only in IE4+ for Windows
   if ((navigator.userAgent.indexOf("Win") != -1) && navigator.userProfile) {
       var newRow, newCell, attrValue
       // queue up requests for every vCard attribute
       for (var i = 0; i < attrs.length; i++) {
           navigator.userProfile.addReadRequest("vCard." + attrs[i])
       }
       // dispatch the request to let user accept or deny access

navigator.userProfile.doReadRequest(1, "JavaScript Bible")

       // append rows to the table with attribute/value pairs
       for (var j = 0; j < attrs.length; j++) {
           newRow = document.all.attrTable.insertRow(-1)
           newRow.bgColor = "#FFFF99"
           newCell = newRow.insertCell(0)
           newCell.innerText = "vCard." + attrs[j]
           newCell = newRow.insertCell(1)
           // get the actual value
           attrValue = navigator.userProfile.getAttribute("vCard." + attrs[j])
           newCell.innerHTML = (attrValue) ? attrValue : " "
       }
       // clean up after ourselves
       navigator.userProfile.clearRequest()
   } else {
       alert("This example requires IE4+ for Windows.")
   }

} </SCRIPT> </HEAD> <BODY onLoad="loadTable()">

userProfile Object


vCard PropertyValue

</BODY> </HTML>


 </source>
   
  


Adding cells to a table row

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function addCell(){

   var x=document.getElementById("myTable").rows[0]
   var y=x.insertCell(2)
   y.innerHTML="NEW CELL"

} </script> </head> <body>

d d
d d
1 2

<form> <input type="button" onclick="addCell()" value="Add cell"> </form> </body> </html>


 </source>
   
  


Adding table rows

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function insRow(){

   var x=document.getElementById("myTable").insertRow(2)
   var y=x.insertCell(0)
   var z=x.insertCell(1)
   y.innerHTML="NEW CELL1"
   z.innerHTML="NEW CELL2"

} </script> </head> <body>

d d
d d
Row3 cell1 Row3 cell2
Row4 cell1 Row4 cell2
Row5 cell1 Row5 cell2

<form> <input type="button" onclick="insRow()" value="Insert row"> </form> </body> </html>


 </source>
   
  


Align the cell content in a single cell

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function alignCell(){

   var x=document.getElementById("myTable").rows[0].cells
   x[0].align="center"

} </script> </head> <body>

First cell Second cell
Third cell Fourth cell

<form> <input type="button" onclick="alignCell()" value="Align cell content"> </form> </body> </html>


 </source>
   
  


Align the cell content in a table row

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function alignRow(){

   var x=document.getElementById("myTable").rows
   x[0].align="right"

} </script> </head> <body>

1 2
1 2
1 2

<form> <input type="button" onclick="alignRow()" value="Align first row"> </form> </body> </html>


 </source>
   
  


Change table border width and cell padding

   <source lang="html4strict">
 

<html> <head> <title>Build-o-Table</title> <script type="text/javascript"> function procImage() {

  var tbl = document.getElementById("table1");
  tbl.border="5px";
  tbl.cellPadding="5px";

} </script> <body onload="procImage();">

adsf

</body> </html>


 </source>
   
  


Change table row height

   <source lang="html4strict">

<html> <head> <script type="text/javascript">

   function specifyRow(){
       var x=document.getElementById("myTable").rows
       x[1].height="100"
   }

</script> </head> <body>

d d
d d
Row3 cell1 Row3 cell2
Row4 cell1 Row4 cell2
Row5 cell1 Row5 cell2

<form>

   <input type="button" onclick="specifyRow()" value="Change height of third row">

</form> </body> </html>


 </source>
   
  


Change the cell content in a table row

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function changeContent(){

   var x=document.getElementById("myTable").rows
   var y=x[0].cells
   y[0].innerHTML="NEW CONTENT"

} </script> </head> <body>

d d
d d

<form> <input type="button" onclick="changeContent()" value="Change content"> </form> </body> </html>


 </source>
   
  


Change the cellPadding and cellSpacing of a table

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function padding(){

   document.getElementById("myTable").cellPadding="25"

} function spacing(){

   document.getElementById("myTable").cellSpacing="25"

} </script> </head> <body>

a b
c d

<form>

   <input type="button" onclick="padding()" value="Change Cellpadding">
   <input type="button" onclick="spacing()" value="Change Cellspacing">

</form> </body> </html>


 </source>
   
  


Change the colspan of a table row

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function setColSpan(){

   var x=document.getElementById("myTable").rows[0].cells
   x[0].colSpan="2"
   x[1].colSpan="6"

} </script> </head> <body>

cell 1 cell 2
cell 3 cell 4 cell 5 cell 6 cell 7 cell 8 cell 9 cell 10

<form> <input type="button" onclick="setColSpan()" value="Change colspan"> </form> </body> </html>


 </source>
   
  


Change the width of a table border

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function changeBorder(){

   document.getElementById("myTable").border="20"

} </script> </head> <body>

a b
c d

<form>

   <input type="button" onclick="changeBorder()" value="Change Border">

</form> </body> </html>


 </source>
   
  


Create a table

   <source lang="html4strict">

<head> <title></title> </script> </head> <body>

<script type = "text/javascript" > var table = document.createElement("table"); table.border = "1"; var tbody = document.createElement("tbody"); table.appendChild(tbody); var row = document.createElement("tr"); for (i = 1; i < 3; i++) {

   var row = document.createElement("tr");
   for (j = 1; j < 3; j++) {
       var td = document.createElement("td");
       var data = document.createTextNode("Row " + i + ", Column " + j);
       td.appendChild(data);
       row.appendChild(td);
   }
   tbody.appendChild(row);

} document.getElementById("thetable").appendChild(table); </script> </body>

 </source>
   
  


Create table caption

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function caption(){

   var x=document.getElementById("myTable").createCaption()
   x.innerHTML="My table caption"

} </script> </head> <body>

d d
d d
Row3 cell1 Row3 cell2

<form> <input type="button" onclick="caption()" value="Create caption"> </form> </body> </html>


 </source>
   
  


Cycling Through Table frame Property Values

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman Publisher: John Wiley & Sons CopyRight 2001 ISBN: 0764533428

  • /

<HTML> <HEAD> <TITLE>TABLE.frame Property</TITLE> <SCRIPT LANGUAGE="JavaScript"> var timeoutID var frameValues = ["box", "above", "rhs", "below", "lhs", "hsides", "vsides",

                  "border", "void"]

function rotateBorder(i) {

   document.getElementById("myTABLE").frame = frameValues[i]
   document.getElementById("myCAPTION").innerHTML = frameValues[i]
   i = (++i == frameValues.length) ? 0 : i
   timeoutID = setTimeout("rotateBorder(" + i + ")", 2000)

} function stopRotate() {

   clearTimeout(timeoutID)
   document.getElementById("myTABLE").frame = "box"
   document.getElementById("myCAPTION").innerHTML = "box"

} </SCRIPT> </HEAD> <BODY>

TABLE.frame Property


<FORM NAME="controls"> <FIELDSET> <LEGEND>Cycle Table Edge Visibility</LEGEND>

<INPUT TYPE="button" VALUE="Cycle" onClick="rotateBorder(0)"> <INPUT TYPE="button" VALUE="Stop" onClick="stopRotate()">

</FIELDSET> </TABLE> </FIELDSET> </FORM>


<THEAD ID="myTHEAD"> </THEAD> <TBODY>
Default
RiverOutflowMilesKilometers
NileMediterranean41606700
CongoAtlantic Ocean29004670
NigerAtlantic Ocean26004180
ZambeziIndian Ocean17002740

</BODY> </HTML>


 </source>
   
  


Cycling Through Table rows Property Values

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman Publisher: John Wiley & Sons CopyRight 2001 ISBN: 0764533428

  • /

<HTML> <HEAD> <TITLE>TABLE.rules Property</TITLE> <SCRIPT LANGUAGE="JavaScript"> var timeoutID var rulesValues = ["all", "cols", "groups", "none", "rows"] function rotateBorder(i) {

   document.getElementById("myTABLE").rules = rulesValues[i]
   document.getElementById("myCAPTION").innerHTML = rulesValues[i]
   i = (++i == rulesValues.length) ? 0 : i
   timeoutID = setTimeout("rotateBorder(" + i + ")", 2000)

} function stopRotate() {

   clearTimeout(timeoutID)
   document.getElementById("myTABLE").rules = "all"
   document.getElementById("myCAPTION").innerHTML = "all"

} </SCRIPT> </HEAD> <BODY>

TABLE.rules Property


<FORM NAME="controls"> <FIELDSET> <LEGEND>Cycle Table Rule Visibility</LEGEND>

<INPUT TYPE="button" VALUE="Cycle" onClick="rotateBorder(0)"> <INPUT TYPE="button" VALUE="Stop" onClick="stopRotate()">

</FIELDSET> </TABLE> </FIELDSET> </FORM>


<COLGROUP SPAN=1> <COLGROUP SPAN=3> <THEAD ID="myTHEAD"> </THEAD> <TBODY>
Default
RiverOutflowMilesKilometers
NileMediterranean41606700
CongoAtlantic Ocean29004670
NigerAtlantic Ocean26004180
ZambeziIndian Ocean17002740

</BODY> </HTML>


 </source>
   
  


Deleting table rows

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function deleteRow(i){

   document.getElementById("myTable").deleteRow(i)

} </script> </head> <body>

Row 1 <input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)">
Row 2 <input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)">
Row 3 <input type="button" value="Delete" onclick="deleteRow(this.parentNode.parentNode.rowIndex)">

</body> </html>


 </source>
   
  


Inserting/Removing Row Elements

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Modifying Table Cell Content</TITLE> <STYLE TYPE="text/css"> THEAD {background-color:lightyellow; font-weight:bold} TFOOT {background-color:lightgreen; font-weight:bold}

  1. myTABLE {background-color:bisque}

</STYLE> <SCRIPT LANGUAGE="JavaScript"> var theTable, theTableBody function init() {

   theTable = (document.all) ? document.all.myTABLE : 
       document.getElementById("myTABLE")
   theTableBody = theTable.tBodies[0]

} function appendRow(form) {

   insertTableRow(form, -1)

} function addRow(form) {

   insertTableRow(form, form.insertIndex.value)

} function insertTableRow(form, where) {

   var now = new Date()
   var nowData = [now.getHours(), now.getMinutes(), now.getSeconds(), 
       now.getMilliseconds()]
   clearBGColors()
   var newCell
   var newRow = theTableBody.insertRow(where)
   for (var i = 0; i < nowData.length; i++) {
       newCell = newRow.insertCell(i)
       newCell.innerHTML = nowData[i]
       newCell.style.backgroundColor = "salmon"
   }
   updateRowCounters(form)

} function removeRow(form) {

   theTableBody.deleteRow(form.deleteIndex.value)
   updateRowCounters(form)

} function insertTHEAD(form) {

   var THEADData = ["Hours","Minutes","Seconds","Milliseconds"]
   var newCell
   var newTHEAD = theTable.createTHead()
   newTHEAD.id = "myTHEAD"
   var newRow = newTHEAD.insertRow(-1)
   for (var i = 0; i < THEADData.length; i++) {
       newCell = newRow.insertCell(i)
       newCell.innerHTML = THEADData[i]
   }
   updateRowCounters(form)
   form.addTHEAD.disabled = true
   form.deleteTHEAD.disabled = false

} function removeTHEAD(form) {

   theTable.deleteTHead()    
   updateRowCounters(form)
   form.addTHEAD.disabled = false
   form.deleteTHEAD.disabled = true

} function insertTFOOT(form) {

   var TFOOTData = ["Hours","Minutes","Seconds","Milliseconds"]
   var newCell
   var newTFOOT = theTable.createTFoot()
   newTFOOT.id = "myTFOOT"
   var newRow = newTFOOT.insertRow(-1)
   for (var i = 0; i < TFOOTData.length; i++) {
       newCell = newRow.insertCell(i)
       newCell.innerHTML = TFOOTData[i]
   }
   updateRowCounters(form)
   form.addTFOOT.disabled = true
   form.deleteTFOOT.disabled = false

} function removeTFOOT(form) {

   theTable.deleteTFoot()    
   updateRowCounters(form)
   form.addTFOOT.disabled = false
   form.deleteTFOOT.disabled = true

} function insertCaption(form) {

   var captionData = form.captionText.value
   var newCaption = theTable.createCaption()
   newCaption.innerHTML = captionData
   form.addCaption.disabled = true
   form.deleteCaption.disabled = false

} function removeCaption(form) {

   theTable.deleteCaption()    
   form.addCaption.disabled = false
   form.deleteCaption.disabled = true

} // housekeeping functions function updateRowCounters(form) {

   var sel1 = form.insertIndex
   var sel2 = form.deleteIndex
   sel1.options.length = 0
   sel2.options.length = 0
   for (var i = 0; i < theTableBody.rows.length; i++) {
       sel1.options[i] = new Option(i, i)
       sel2.options[i] = new Option(i, i)
   }
   form.removeRowBtn.disabled = (i==0)

} function clearBGColors() {

   for (var i = 0; i < theTableBody.rows.length; i++) {
       for (var j = 0; j < theTableBody.rows[i].cells.length; j++) {
           theTableBody.rows[i].cells[j].style.backgroundColor = ""        
       }
   }

} </SCRIPT> </HEAD> <BODY onLoad="init()">

Modifying Tables


<FORM NAME="controls"> <FIELDSET> <LEGEND>Add/Remove Rows</LEGEND>

<INPUT TYPE="button" VALUE="Append 1 Row" onClick="appendRow(this.form)"> <INPUT TYPE="button" VALUE="Insert 1 Row" onClick="addRow(this.form)"> at index:
   <SELECT NAME="insertIndex">
       <OPTION VALUE="0">0
</SELECT>
<INPUT TYPE="button" NAME="removeRowBtn" VALUE="Delete 1 Row" DISABLED
   onClick="removeRow(this.form)"> at index: 
   <SELECT NAME="deleteIndex">
       <OPTION VALUE="0">0
</SELECT>

</FIELDSET> <FIELDSET> <LEGEND>Add/Remove THEAD and TFOOT</LEGEND>

<INPUT TYPE="button" NAME="addTHEAD" VALUE="Insert THEAD"
   onClick="insertTHEAD(this.form)">
<INPUT TYPE="button" NAME="deleteTHEAD" VALUE="Remove THEAD" DISABLED onClick="removeTHEAD(this.form)">
<INPUT TYPE="button" NAME="addTFOOT" VALUE="Insert TFOOT"
   onClick="insertTFOOT(this.form)">
<INPUT TYPE="button" NAME="deleteTFOOT" VALUE="Remove TFOOT" DISABLED onClick="removeTFOOT(this.form)">

</FIELDSET> <FIELDSET> <LEGEND>Add/Remove Caption</LEGEND>

<INPUT TYPE="button" NAME="addCaption" VALUE="Add Caption" onClick="insertCaption(this.form)"> Text: <INPUT TYPE="text" NAME="captionText" SIZE=40 VALUE="Sample Caption"> <INPUT TYPE="button" NAME="deleteCaption" VALUE="Delete Caption" DISABLED onClick="removeCaption(this.form)">

</FIELDSET> </FORM>


<TBODY>

</BODY> </HTML>


 </source>
   
  


Insert table row: the uniqueID Property

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Inserting an IE5+/Windows Table Row</TITLE> <SCRIPT LANGUAGE="JavaScript"> function addRow(item1) {

   if (item1) {
       // assign long reference to shorter var name
       var theTable = document.all.myTable
       // append new row to the end of the table
       var newRow = theTable.insertRow(theTable.rows.length)
       // give the row its own ID
       newRow.id = newRow.uniqueID
       
       // declare cell variable
       var newCell
       
       // an inserted row has no cells, so insert the cells
       newCell = newRow.insertCell(0)
       // give this cell its own id
       newCell.id = newCell.uniqueID
       // display the row"s id as the cell text
       newCell.innerText = newRow.id
       newCell.bgColor = "yellow"
       // reuse cell var for second cell insertion
       newCell = newRow.insertCell(1)
       newCell.id = newCell.uniqueID
       newCell.innerText = item1
   }

} </SCRIPT> </HEAD> <BODY>

Row ID Data
firstDataRow Fred
secondDataRow Jane

<FORM> Enter text to be added to the table:
<INPUT TYPE="text" NAME="input" SIZE=25>
<INPUT TYPE="button" VALUE="Insert Row" onClick="addRow(this.form.input.value)"> </FORM> </BODY> </HTML>


 </source>
   
  


Modifying Table Columns

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Modifying Table Columns</TITLE> <STYLE TYPE="text/css"> THEAD {background-color:lightyellow; font-weight:bold} .rankCells {background-color:lightgreen; font-weight:bold}

  1. myTABLE {background-color:bisque}

</STYLE> <SCRIPT LANGUAGE="JavaScript"> var theTable, theTableBody function init() {

   theTable = (document.all) ? document.all.myTABLE : 
       document.getElementById("myTABLE")
   theTableBody = theTable.tBodies[0]

} function insertColumn(form) {

   var oneRow, newCell, rank
   if (theTable.tHead) {
       oneRow = theTable.tHead.rows[0]
       newCell = oneRow.insertCell(0)
       newCell.innerHTML = "Ranking"
   }
   rank = 1
   for (var i = 0; i < theTableBody.rows.length; i++) {
       oneRow = theTableBody.rows[i]
       newCell = oneRow.insertCell(0)
       newCell.className = "rankCells"
       newCell.innerHTML = rank++
   }
   form.addColumn.disabled = true
   form.removeColumn.disabled = false

} function deleteColumn(form) {

   var oneRow
   if (theTable.tHead) {
       oneRow = theTable.tHead.rows[0]
       oneRow.deleteCell(0)
   }
   for (var i = 0; i < theTableBody.rows.length; i++) {
       oneRow = theTableBody.rows[i]
       oneRow.deleteCell(0)
   }
   form.addColumn.disabled = false
   form.removeColumn.disabled = true

} </SCRIPT> </HEAD> <BODY onLoad="init()">

Modifying Table Columns


<FORM NAME="controls"> <FIELDSET> <LEGEND>Add/Remove Left Column</LEGEND>

<INPUT TYPE="button" NAME="addColumn" VALUE="Insert Left Column" onClick="insertColumn(this.form)"> <INPUT TYPE="button" NAME="removeColumn" VALUE="Remove Left Column" DISABLED onClick="deleteColumn(this.form)">

</FIELDSET> </TABLE> </FIELDSET> </FORM>


<THEAD ID="myTHEAD"> </THEAD> <TBODY>
RiverOutflowMilesKilometers
NileMediterranean41606700
CongoAtlantic Ocean29004670
NigerAtlantic Ocean26004180
ZambeziIndian Ocean17002740

</BODY> </HTML>


 </source>
   
  


Replacing Table Cell Content

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Modifying Table Cell Content</TITLE> <STYLE TYPE="text/css"> .absoluteWrap {position:absolute} .relativeWrap {position:relative} .total {color:red} </STYLE> <SCRIPT LANGUAGE="JavaScript"> var Ver4 = parseInt(navigator.appVersion) == 4 var Ver4Up = parseInt(navigator.appVersion) >= 4 var Nav4 = ((navigator.appName == "Netscape") && Ver4) var modifiable // calculate and display a row"s total function showTotal(qtyList) {

   var qty = qtyList.options[qtyList.selectedIndex].value
   var prodID = qtyList.name
   var total = "US$" + 
       (qty * parseFloat(qtyList.form.elements[prodID + "Price"].value))
   var newCellHTML = "" + total + ""
   if(Nav4) {
       document.layers[prodID + "TotalWrapper"].document.layers[prodID + 
           "Total"].document.write(newCellHTML)
       document.layers[prodID + "TotalWrapper"].document.layers[prodID + 
           "Total"].document.close()
   } else if (modifiable) {
       if (document.all) {
           document.all(prodID + "Total").innerHTML = newCellHTML
       } else {
           document.getElementById(prodID + "Total").innerHTML = newCellHTML
       }
   }

} // initialize global flag for browsers capable of modifiable content function init() {

   modifiable  = (Ver4Up && document.body && document.body.innerHTML)

} // display content for all products (e.g., in case of Back navigation) function showAllTotals(form) {

   for (var i = 0; i < form.elements.length; i++) {
       if (form.elements[i].type == "select-one") {        
           showTotal(form.elements[i])
       }        
   }

} </SCRIPT> </HEAD> <BODY onLoad="init(); showAllTotals(document.orderForm)">

Modifying Table Cell Content


<FORM NAME="orderForm">

<COLGROUP WIDTH=150> <COLGROUP WIDTH=100> <COLGROUP WIDTH=50> <COLGROUP WIDTH=100
Product Description Price Each Quantity Total
Wonder Widget 9000 US$125.00 <SELECT NAME="ww9000" onChange="showTotal(this)">
       <OPTION VALUE="0">0
       <OPTION VALUE="1">1
       <OPTION VALUE="2">2
       <OPTION VALUE="3">3
       </SELECT>
<INPUT TYPE="hidden" NAME="ww9000Price" VALUE="125.00">
   <SCRIPT LANGUAGE="JavaScript">
   if (Nav4) {

var placeHolder = "        "

       placeHolder += "       "
       document.write("")
       document.write("")
       document.write("" + placeHolder + "")
   } else {
       document.write("" + 
"

 

")
   }
   </SCRIPT>

</FORM> </BODY> </HTML>


 </source>
   
  


Specify frames of a table

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function aboveFrames(){

   document.getElementById("myTable").frame="above"

} function belowFrames(){

   document.getElementById("myTable").frame="below"

} </script> </head> <body>

a b
c d

<form>

   <input type="button" onclick="aboveFrames()" value="Show above frames">
   <input type="button" onclick="belowFrames()" value="Show below frames">

</form> </body> </html>


 </source>
   
  


Specify rules for a table

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function rowRules(){

   document.getElementById("myTable").rules="rows"

} function colRules(){

   document.getElementById("myTable").rules="cols"

} </script> </head> <body>

d d
d d
Row3 cell1 Row3 cell2
Row4 cell1 Row4 cell2
Row5 cell1 Row5 cell2

<form> <input type="button" onclick="rowRules()" value="Show row borders"> <input type="button" onclick="colRules()" value="Show col borders"> </form> </body> </html>


 </source>
   
  


Tabular data in Javascript with hyper link

   <source lang="html4strict">


<html> <head> <title>Dynamic Table</title> <style type="text/css"> body {background-color:#ffffff} table {table-collapse:collapse; border-spacing:0} td {border:2px groove black; padding:7px} th {border:2px groove black; padding:7px} .ctr {text-align:center} </style> <script language="JavaScript" type="text/javascript"> // Table data -- an array of objects var jsData = new Array(); jsData[0] = {bowl:"I", year:1967, winner:"Packers", winScore:35, loser:"Chiefs", losScore:10}; jsData[1] = {bowl:"II", year:1968, winner:"Packers", winScore:33, loser:"Raiders (Oakland)", losScore:14}; jsData[2] = {bowl:"III", year:1969, winner:"Jets", winScore:16, loser:"Colts (Balto)", losScore:7}; jsData[3] = {bowl:"IV", year:1970, winner:"Chiefs", winScore:23, loser:"Vikings", losScore:7}; jsData[4] = {bowl:"V", year:1971, winner:"Colts (Balto)", winScore:16, loser:"Cowboys", losScore:13}; // Sorting functions (invoked by sortTable()) function sortByYear(a, b) {

   return a.year - b.year;

} function sortByWinScore(a, b) {

   return b.winScore - a.winScore;

} function sortByLosScore(a, b) {

   return b.losScore - a.losScore;

} function sortByWinner(a, b) {

   a = a.winner.toLowerCase();
   b = b.winner.toLowerCase();
   return ((a < b) ? -1 : ((a > b) ? 1 : 0));

} function sortByLoser(a, b) {

   a = a.loser.toLowerCase();
   b = b.loser.toLowerCase();
   return ((a < b) ? -1 : ((a > b) ? 1 : 0));

} // Sorting function dispatcher (invoked by table column links) function sortTable(link) {

   switch (link.firstChild.nodeValue) {
       case "Year" :
           jsData.sort(sortByYear);
           break;
       case "Winner" :
           jsData.sort(sortByWinner);
           break;
       case "Loser" :
           jsData.sort(sortByLoser);
           break;
       case "Win" :
           jsData.sort(sortByWinScore);
           break;
       case "Lose" :
           jsData.sort(sortByLosScore);
           break;
   }
   drawTable("bowlData")

} // Remove existing table rows function clearTable(tbody) {

   while (tbody.rows.length > 0) {
       tbody.deleteRow(0);
   }

} // Draw table from "jsData" array of objects function drawTable(tbody) {

   var tr, td;
   tbody = document.getElementById(tbody);
   // remove existing rows, if any
   clearTable(tbody);
   // loop through data source
   for (var i = 0; i < jsData.length; i++) {
       tr = tbody.insertRow(tbody.rows.length);
       td = tr.insertCell(tr.cells.length);
       td.setAttribute("class", "ctr");
       td.innerHTML = jsData[i].bowl;
       td = tr.insertCell(tr.cells.length);
       td.innerHTML = jsData[i].year;
       td = tr.insertCell(tr.cells.length);
       td.innerHTML = jsData[i].winner;
       td = tr.insertCell(tr.cells.length);
       td.innerHTML = jsData[i].loser;
       td = tr.insertCell(tr.cells.length);
       td.setAttribute("class", "ctr");
       td.innerHTML = jsData[i].winScore + " - " + jsData[i].losScore;
   }

} </script> </head> <body onload="drawTable("bowlData")">

Super Bowl Games


<thead> </thead> <tbody id="bowlData"></tbody>
Bowl <a href="#" title="Sort by Year" onclick="sortTable(this)">Year</a> <a href="#" title="Sort by Winning Team" onclick="sortTable(this)">Winner</a> <a href="#" title="Sort by Losing Team" onclick="sortTable(this)">Loser</a> Score <a href="#" title="Sort by Winning Score"
   onclick="sortTable(this)">Win</a> - <a href="#" 
title="Sort by Losing Score" onclick="sortTable(this)">Lose</a>

</body> </html>


 </source>
   
  


Transforming JavaScript Data into HTML Tables

   <source lang="html4strict">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">

<html> <head> <title>Recipe 14.7</title> <link rel="stylesheet" id="mainStyle" href="../css/cookbook.css" type="text/css" /> <style type="text/css"> table {table-collapse:collapse; border-spacing:0} td {border:2px groove black; padding:7px; background-color:#ccffcc} th {border:2px groove black; padding:7px; background-color:#ffffcc} .ctr {text-align:center} </style> <script type="text/javascript"> // Table data -- an array of objects var jsData = new Array(); jsData[0] = {location:"Uruguay", year:1930, winner:"Uruguay", winScore:4,

            loser:"Argentina", losScore:2};

jsData[1] = {location:"Italy", year:1934, winner:"Italy", winScore:2,

            loser:"Czechoslovakia", losScore:1};

jsData[2] = {location:"France", year:1938, winner:"Italy", winScore:4,

            loser:"Hungary", losScore:2};

jsData[3] = {location:"Brazil", year:1950, winner:"Uruguay", winScore:2,

            loser:"Brazil", losScore:1};

jsData[4] = {location:"Switzerland", year:1954, winner:"West Germany", winScore:3,

            loser:"Hungary", losScore:2};

// Draw table from "jsData" array of objects function drawTable(tbody) {

   var tr, td;
   tbody = document.getElementById(tbody);
   // loop through data source
   for (var i = 0; i < jsData.length; i++) {
       tr = tbody.insertRow(tbody.rows.length);
       td = tr.insertCell(tr.cells.length);
       td.setAttribute("align", "center");
       td.innerHTML = jsData[i].year;
       td = tr.insertCell(tr.cells.length);
       td.innerHTML = jsData[i].location;
       td = tr.insertCell(tr.cells.length);
       td.innerHTML = jsData[i].winner;
       td = tr.insertCell(tr.cells.length);
       td.innerHTML = jsData[i].loser;
       td = tr.insertCell(tr.cells.length);
       td.setAttribute("align", "center");
       td.innerHTML = jsData[i].winScore + " - " + jsData[i].losScore;
   }

} </script> </head> <body onload="drawTable("matchData")">

Transforming JavaScript Data into HTML Tables


<thead> </thead> <tbody id="matchData"></tbody>
Year Host Country Winner Loser Score (Win - Lose)

</body> </html>


 </source>
   
  


Transforming JavaScript Data into HTML Tables with HyperLink

   <source lang="html4strict">

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
 "http://www.w3.org/tr/xhtml1/DTD/xhtml1-transitional.dtd">

<html> <head> <title>Recipe 14.16</title> <style rel="stylesheet" id="mainStyle" type="text/css"> html {background-color:#cccccc} body {background-color:#eeeeee; font-family:Tahoma,Arial,Helvetica,sans-serif; font-size:12px;

   margin-left:15%; margin-right:15%; border:3px groove darkred; padding:15px}

h1 {text-align:right; font-size:1.5em; font-weight:bold} h2 {text-align:left; font-size:1.1em; font-weight:bold; text-decoration:underline} .buttons {margin-top:10px}

</style> <style type="text/css"> table {table-collapse:collapse; border-spacing:0} td {border:2px groove black; padding:7px; background-color:#ccffcc} th {border:2px groove black; padding:7px; background-color:#ffffcc} .ctr {text-align:center} </style> <script type="text/javascript"> // Table data -- an array of objects var jsData = new Array(); jsData[0] = {location:"Uruguay", year:1930, winner:"Uruguay", winScore:4,

            loser:"Argentina", losScore:2};

jsData[1] = {location:"Italy", year:1934, winner:"Italy", winScore:2,

            loser:"Czechoslovakia", losScore:1};

jsData[2] = {location:"France", year:1938, winner:"Italy", winScore:4,

            loser:"Hungary", losScore:2};

jsData[3] = {location:"Brazil", year:1950, winner:"Uruguay", winScore:2,

            loser:"Brazil", losScore:1};

jsData[4] = {location:"Switzerland", year:1954, winner:"West Germany", winScore:3,

            loser:"Hungary", losScore:2};

// Draw table from "jsData" array of objects function drawTable(tbody) {

   var tr, td;
   tbody = document.getElementById(tbody);
   // remove existing rows, if any
   clearTable(tbody);
   // loop through data source
   for (var i = 0; i < jsData.length; i++) {
       tr = tbody.insertRow(tbody.rows.length);
       td = tr.insertCell(tr.cells.length);
       td.setAttribute("align", "center");
       td.innerHTML = jsData[i].year;
       td = tr.insertCell(tr.cells.length);
       td.innerHTML = jsData[i].location;
       td = tr.insertCell(tr.cells.length);
       td.innerHTML = jsData[i].winner;
       td = tr.insertCell(tr.cells.length);
       td.innerHTML = jsData[i].loser;
       td = tr.insertCell(tr.cells.length);
       td.setAttribute("align", "center");
       td.innerHTML = jsData[i].winScore + " - " + jsData[i].losScore;
   }

} // Remove existing table rows function clearTable(tbody) {

   while (tbody.rows.length > 0) {
       tbody.deleteRow(0);
   }

} // Sorting function dispatcher (invoked by table column links) function sortTable(link) {

   switch (link.firstChild.nodeValue) {
       case "Year" :
           jsData.sort(sortByYear);
           break;
       case "Host Country" :
           jsData.sort(sortByHost);
           break;
       case "Winner" :
           jsData.sort(sortByWinner);
           break;
       case "Loser" :
           jsData.sort(sortByLoser);
           break;
       case "Win" :
           jsData.sort(sortByWinScore);
           break;
       case "Lose" :
           jsData.sort(sortByLosScore);
           break;
   }
   drawTable("matchData")
   return false

} // Sorting functions (invoked by sortTable()) function sortByYear(a, b) {

   return a.year - b.year;

} function sortByHost(a, b) {

   a = a.location.toLowerCase();
   b = b.location.toLowerCase();
   return ((a < b) ? -1 : ((a > b) ? 1 : 0));

} function sortByWinScore(a, b) {

   return b.winScore - a.winScore;

} function sortByLosScore(a, b) {

   return b.losScore - a.losScore;

} function sortByWinner(a, b) {

   a = a.winner.toLowerCase();
   b = b.winner.toLowerCase();
   return ((a < b) ? -1 : ((a > b) ? 1 : 0));

} function sortByLoser(a, b) {

   a = a.loser.toLowerCase();
   b = b.loser.toLowerCase();
   return ((a < b) ? -1 : ((a > b) ? 1 : 0));

} </script> </head> <body onload="drawTable("matchData")">

Transforming JavaScript Data into HTML Tables


<thead> </thead> <tbody id="matchData"></tbody>
<a href="#" title="Sort by Year" onclick="return sortTable(this)">Year</a> <a href="#" title="Sort by Country" onclick="return sortTable(this)">Host Country</a> <a href="#" title="Sort by Winning Team" onclick="return sortTable(this)">Winner</a> <a href="#" title="Sort by Losing Team" onclick="return sortTable(this)">Loser</a> Score <a href="#" title="Sort by Winning Score"
                onclick="return sortTable(this)">Win</a> - <a href="#" 
                title="Sort by Losing Score" 
onclick="return sortTable(this)">Lose</a>

</body> </html>


 </source>
   
  


Using the cloneNode Method

   <source lang="html4strict">

/* JavaScript Unleashed, Third Edition by Richard Wagner and R. Allen Wyke ISBN: 067231763X Publisher Sams CopyRight 2000

  • /

<HTML> <HEAD> <TITLE> DOM cloneNode example </TITLE> </HEAD> <BODY ID="bodyNode">

<TBODY> </TBODY>
Row 1, Cell 1 Row 1, Cell 2
Row 2, Cell 1 Row 2, Cell 2
Row 3, Cell 1 Row 3, Cell 2
Row 4, Cell 1 Row 4, Cell 2
Row 5, Cell 1 Row 5, Cell 2

<SCRIPT LANGUAGE="JavaScript">

</SCRIPT> </BODY> </HTML>


 </source>
   
  


Using the Data Binding record Number Property

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>Data Binding (recordNumber)</TITLE> <STYLE TYPE="text/css"> .filmTitle {font-style:italic} </STYLE> <SCRIPT LANGUAGE="JavaScript"> // set recordset pointer to the record clicked on in the table. function setRecNum(row) {

   document.oscars.recordset.AbsolutePosition = row.recordNumber

} </SCRIPT> </HEAD> <BODY>

Academy Awards 1978-1997 (Click on a table row to extract data from one record.)

The award for Best Actor of  went to  for his outstanding achievement in the film .

<THEAD STYLE="background-color:yellow; text-align:center"> </THEAD>
Year Film Director Actress Actor

<OBJECT ID="oscars" CLASSID="clsid:333C7BC4-460F-11D0-BC04-0080C7055A83">

   <PARAM NAME="DataURL" VALUE="Academy Awards.txt">
   <PARAM NAME="UseHeader" VALUE="True">
   <PARAM NAME="FieldDelim" VALUE="	">

</OBJECT> </BODY> </HTML>


 </source>
   
  


Using the offsetParent Property

   <source lang="html4strict">

/* JavaScript Bible, Fourth Edition by Danny Goodman John Wiley & Sons CopyRight 2001

  • /

<HTML> <HEAD> <TITLE>offsetParent Property</TITLE> <SCRIPT LANGUAGE="JavaScript"> function setImagePosition(){

   var cElement = document.all.myCell
   // Set flag for whether calculations should use
   // client- or offset- property measures. Use
   // client- for IE5/Mac and IE4/Windows; otherwise
   // use offset- properties. An ugly, but necessary
   // workaround.
   var useClient = (cElement.offsetTop == 0) ? 
       ((cElement.offsetParent.tagName == "TR") ? false : true) : false
   if (useClient) {
       var x = cElement.clientLeft
       var y = cElement.clientTop
   } else {
       var x = cElement.offsetLeft
       var y = cElement.offsetTop
   }
   var pElement = document.all.myCell.offsetParent
   while (pElement != document.body) {
       if (useClient) {
           x += pElement.clientLeft
           y += pElement.clientTop
       } else {
           x += pElement.offsetLeft
           y += pElement.offsetTop
       }
       pElement = pElement.offsetParent
   }
   document.all.myDIV.style.pixelLeft = x
   document.all.myDIV.style.pixelTop = y
   document.all.myDIV.style.visibility = "visible"

} </SCRIPT> </HEAD> <BODY onload="setImagePosition()"> <SCRIPT LANGUAGE="JavaScript"> </SCRIPT>

The offsetParent Property


After the document loads, the script positions a small image in the upper left corner of the second table cell.

This is the first cell This is the second cell.

</BODY> </HTML>


 </source>
   
  


Vertical align the cell content in a single cell

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function valignCell(){

   var x=document.getElementById("myTable").rows[0].cells
   x[0].vAlign="bottom"

} </script> </head> <body>

l l
l l

<form> <input type="button" onclick="valignCell()" value="Vertical align cell content"> </form> </body> </html>



 </source>
   
  


Vertical align the cell content in a table row

   <source lang="html4strict">

<html> <head> <script type="text/javascript"> function valignRow(){

   var x=document.getElementById("myTable").rows
   x[0].vAlign="top"

} </script> </head> <body>

1 2
1 2
1 2

<form> <input type="button" onclick="valignRow()" value="Vertical align row"> </form> </body> </html>


 </source>