Posts Tagged ‘add class by jquery’

A simple trick to apply alternate css class part 1

March 27, 2009

In our professional work sometimes we  need to apply some simple trick to overcome complexity when retrieving data from database and showing those on user interface using loop.

Suppose that we have some data from database and showing them using loop on our interface like below –

First one we have designed static so that we can understand the format

<table>
<thead>
<tr>
<td> Username </td>
</tr>
</thead>
<tbody>
<tr>
<td>Shahriat</td>
</tr>
<tr>
<td>Hossain</td>
</tr>
<tr>
<td>Somel</td>
</tr>
</tbody>
</table>

Now we will apply some style here –

table tbody tr
{
background: url(../img/tbody_tr_bg.png) repeat-x left bottom;
}

After applying style we can get the output –

Shahriat
………………………. // dotted is the png image in our style
Hossain
………………………..
Somel
………………………..

Isn’t it very odd to look at our design has broken ? Certainly under Somel dotted (…..) should not be there. It will be then design broken issue. It can be solved if we keep the design static as it is adding extra class at the last row. But what about when we make it dynamic using loop retrieving data from database like below –

foreach($a as $k=>$v){
echo'<tr>’;
echo'<td>’.$v.'</td>’;
echo'</tr>’;
}

Jquery is our best friend here to solve this type of problem and now we will go with a simple example here –

$(“tr:last”).addClass(“no_bg”);

We have added a class no_bg using Jquery addClass method at the last row of table. Here (:last) is one of the Jquery basic filter which finds the last row of table. Its a single code isn’t it and after all getting out here is our complete code –

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=utf-8″ />
<title>Untitled Document</title>

<script src="http://code.jquery.com/jquery-latest.js"></script>

<script>
$(document).ready(function(){
$(“tr:last”).addClass(“no_bg”);
});
</script>
<style>
table tbody tr {
background: url(../img/tbody_tr_bg.png) repeat-x left bottom;
}
.no_bg {
background: none !important;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<td> Username </td>
</tr>
</thead>
<tbody>
<?php
foreach($a as $k=>$v){
echo'<tr>’;
echo'<td>’.$v.'</td>’;
echo'</tr>’;
}
?>
</tbody>
</table>
</body>
</html>

and the output is –

Shahriat
……………..
Hossain
…………….
Somel
// no background image (………..) here

[It may help you :)]

Advertisements