sarah
sarah

Reputation: 2397

Table Structure in Html

I want to create a table structure with checkbox for each row and each row is identified with different colors, how can I achieve this

Upvotes: 0

Views: 298

Answers (4)

zapping
zapping

Reputation: 4116

To set alternating colors you need to start a loop like

for(i=0;i<no_checkboxes;i++)

Then when you create the rows check if i is even or odd and set colors accordingly

if(i%2)
 <td bgcolor="red">
else
 <td bgcolor="green">

and then enclose the checkboxes.

Here is a sample in php http://lorenzod8n.wordpress.com/2007/06/02/alternating-row-color-in-htmlcss-with-php/

Upvotes: 1

Amarghosh
Amarghosh

Reputation: 59471

CSS:

.odd {
  color:#CCC;
  background-color:#333;
}
.even {
  color:#333;
  background-color:#CCC;
}

HTML:

<table id="tbl">
  <tr class="odd">
   <td><input type="checkbox"/></td>
   <td>First row</td>
  </tr>
  <tr class="even">
   <td><input type="checkbox"/></td>
   <td>Second row</td>
  </tr>
  <tr class="odd">
   <td><input type="checkbox"/></td>
   <td>Third row</td>
  </tr>
</table>

JavaScript:

function addRow(text)
{
  var rows = document.getElementById('tbl').getElementsByTagName('tr');
  var last = rows.item(rows.length - 1);
  var odd = last.getAttribute('class') == "odd"; 
  //use regex instead of == if you plan to have multiple classes for rows

  var row = document.createElement('tr');
  var td = document.createElement('td');
  var ip = document.createElement('input');
  ip.setAttribute('type', 'checkbox');
  td.appendChild(ip);
  tr.appendChild(td);
  td = document.createElement('td');
  td.appendChild(document.createTextNode(text));
  tr.appendChild(td);
  tr.setAttribute('class', odd ? 'even' : 'odd');
  document.getElementById('tbl').appendChild(tr);
}

Add rows using:

addRow("Fourth row");
addRow("Another row");
addRow("One more row");

Upvotes: 2

Orson
Orson

Reputation: 15451

You can get the zebra-sripes (Alternate Colours) using JQuery:

$("table tr:nth-child(even)").addClass("striped");

striped is a class defined in your css and the background of your table forms the other colour.

Upvotes: 0

pixeltocode
pixeltocode

Reputation: 5288

you can use the nth child selector

tr:nth-child(even) {background: #f00;}
tr:nth-child(odd) {background: #0f0;}

see this link

Upvotes: 3

Related Questions