Jump to content

how to highlight table row on select?


geekisthenewsexy

Recommended Posts

hi guys. as stated in my question above, i want to be able to highlight a table row when i click on it and unhighlight when i click on another row. i'm totally new to javascript and jquery so i don't know where to begin. i've used php also on this one to display the records in the table. hope you guys can help. just tell me if something is lacking in the code i've posted or if i need to post javascript. here's the html&php code..

 

<div id="tableheader">		
        	<div class="search">
                <select id="columns" onchange="sorter.search('query')"></select>
                <input type="text" id="query" name="query" onkeyup="sorter.search('query')"/>
            </div>
            <span class="details">
			<div>Records <span id="startrecord"></span>-<span id="endrecord"></span> of <span id="totalrecords"></span></div>
        		<div><a href="javascript:sorter.reset()">Reset</a></div>				
        	</span>

        </div>
  
      <table cellpadding="0" cellspacing="0" border="0" id="table" class="tinytable">
            <thead>
                <tr>
			 <th><h3>ID</h3></th>
                    <th><h3>Course</h3></th>
				<th><h3>Year</h3></th>
                    <th><h3>Block</h3></th>
				<th class="nosort"><h3></h3></th>
                </tr>

            </thead>
            <tbody>
            <?php
		 include("dbcon.php");
	$result = mysql_query("SELECT DISTINCT * FROM course,year,block WHERE course.c_id=year.c_id AND year.y_id=block.y_id") or die(mysql_error());  

	$OutLine = array('OutID'=>'','OutName'=>'','OutYear'=>'','OutBlock'=>'');
	while ($row = mysql_fetch_array($result))
	{
	$OutLine['OutID'] = $row['c_id'];
	$OutLine['OutName'] = $row['c_name'];
	$OutLine['OutYear'] = $row['year'];
	$OutLine['OutBlock'] = $row['block'];
	echo "<tr>";
	echo "<td>".implode('<td/>',$OutLine);
	echo "<input type='hidden' name='id'  value='$row[b_id]'>";
	echo '<td align="center"><div id="imagealign">
            	<div><a href="#" onClick="window.open(\'viewroom.php?id='.$row['b_id'].'&block='.$row['block'].'\',\'Viewrooms\',\'width=350, height=350, menubar=yes\');return false;"><img src="images/magnifier.png" title="View rooms" width="16" height="16" border="0"></a> <a href="#" onClick="window.open(\'room.php?id='.$row['b_id'].'&block='.$row['block'].'\',\'Addrooms\',\'width=300, height=300, menubar=yes\');return false;"><img src="images/add.png"  title="Add rooms" width="16" height="16" border="0"></a> | <a href="#" onClick="window.open(\'edit.php?c_id='.$row['c_id'].'&course='.$row['c_name'].'&y_id='.$row['y_id'].'&year='.$row['year'].'&id='.$row['b_id'].'&block='.$row['block'].'\',\'Edit\',\'width=350, height=300, menubar=yes\');return false;"><img src="images/edit.png" title="Edit block" width="16" height="16" border="0"></a> <a href="delete.php?c_id='.$row['c_id'].'&course='.$row['c_name'].'&y_id='.$row['y_id'].'&year='.$row['year'].'&b_id='.$row['b_id'].'&block='.$row['block'].'" title="Delete this record"onClick="return confirm(\'You are about to delete '.$row['c_name'].', '.$row['year'].', '.$row['block'].'! Delete?\');return false;"><img src="images/del.png" width="16" height="16" border="0" alt="Delete record"></a></div></div></td>';
	echo "</tr>";
	}
	?>           
			</tbody>
        </table>
	  <div id="tablefooter">
          <div id="tablenav">
            	<div>
                    <img src="images/first.gif" width="16" height="16" alt="First Page" onclick="sorter.move(-1,true)" />
                    <img src="images/previous.gif" width="16" height="16" alt="First Page" onclick="sorter.move(-1)" />
                    <img src="images/next.gif" width="16" height="16" alt="First Page" onclick="sorter.move(1)" />
                    <img src="images/last.gif" width="16" height="16" alt="Last Page" onclick="sorter.move(1,true)" />
                </div>
                <div>
                	<select id="pagedropdown"></select>
			</div>
                <div>
                	<a href="javascript:sorter.showall()">View all</a>
                </div>
            </div>
		<div id="tablelocation">
            	<div>
                    <select onchange="sorter.size(this.value)">
                    <option value="5">5</option>
                        <option value="10" selected="selected">10</option>
                        <option value="20">20</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                    </select>
                    <span>Entries Per Page</span>
                </div>
                <div class="page">Page <span id="currentpage"></span>of <span id="totalpages"></span></div>
            </div>
        </div>

Link to comment
Share on other sites

Sorry about the wait. I got a solution.

 

Example CSS:

    <style>
	.highlighted { background:black; color: white; }
	tr { cursor: pointer; }
</style>

 

Example JS:

	<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
	function myfunction (myTD)
	{
   			$(".highlighted").removeClass("highlighted");
    		$(myTD).addClass("highlighted");
	}
</script>

 

Example HTML:

	<table style="border:2px solid blue;" cellspacing="0">
    	<tr onclick="myfunction(this)">
        	<td>TD Box 1</td>
            <td>TD Box 2</td>
        </tr>
    	<tr onclick="myfunction(this)">
        	<td>TD Box 1</td>
            <td>TD Box 2</td>
        </tr>
    </table>

 

This is set so that when you click a row (TR) it'll add the class .highlighted which means the background will be black, text will be white. When clicking the other row (TR) - (Two in this example) it'll remove the class from the previous row (TR) and add it on the one you just clicked.

 

If you want it for TD, just remove the onclick from the TR's and place them in the TD's.

 

There is an easier method that doesn't require onclicks if you'd prefer that but I'd need some time alone to code it first :P

 

Hope this is what you're looking for.

Link to comment
Share on other sites

To do the same as the above. Remove the onclicks, and use this JS instead.

 

    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script type="text/javascript">
        $(function() {
            $('tr').click(function() {
                   $('.highlighted').removeClass("highlighted");
                $(this).addClass("highlighted");
            });
        });
    </script>

To do it with TD's instead of TR's just change 'tr' to 'td'

 

Link to comment
Share on other sites

hi, sorry for the delay.

i tried your code but unfortunately it doesn't seem to work with mine. or maybe i just don't know how to? :P

so i figured posting the entire jscript here..

var TINY={};


function T$(i){return document.getElementById(i)}
function T$$(e,p){return p.getElementsByTagName(e)}


TINY.table=function(){
function sorter(n,t,p){this.n=n; this.id=t; this.p=p; if(this.p.init){this.init()}}
sorter.prototype.init=function(){
	this.set(); var t=this.t, i=d=0; t.h=T$$('tr',t)[0];
	t.l=t.r.length; t.w=t.r[0].cells.length; t.a=[]; t.c=[]; this.p.is=this.p.size;

	if(this.p.colddid){
		d=T$(this.p.colddid);
		var o=document.createElement('option'); o.value=-1; o.innerHTML='All Columns'; d.appendChild(o)
	}
	for(i;i<t.w;i++){
		var c=t.h.cells[i]; t.c[i]={};
		if(c.className!='nosort'){
			c.className=this.p.headclass; c.onclick=new Function(this.n+'.sort('+i+')');
			c.onmousedown=function(){return false};
		}
		if(this.p.columns){
			var l=this.p.columns.length, x=0;
			for(x;x<l;x++){
				if(this.p.columns[x].index==i){
					var g=this.p.columns[x];
					t.c[i].format=g.format==null?1:g.format; t.c[i].decimals=g.decimals==null?2:g.decimals
				}
			}
		}
		if(d){
			var o=document.createElement('option'); o.value=i; o.innerHTML=T$$('h3',c)[0].innerHTML; d.appendChild(o)
		}
	}
	this.reset()
};
sorter.prototype.reset=function(){
	var t=this.t; t.t=t.l;
	for(var i=0;i<t.l;i++){t.a[i]={}; t.a[i].s=1}
	if(this.p.sortcolumn!=undefined){
		this.sort(this.p.sortcolumn,1,this.p.is)
	}else{
		if(this.p.paginate){this.size()} this.alt(); this.sethover()
	}
	this.calc()
};
sorter.prototype.sort=function(x,f,z){
	var t=this.t; t.y=x; var x=t.h.cells[t.y], i=0, n=document.createElement('tbody');
	for(i;i<t.l;i++){
		t.a[i].o=i; var v=t.r[i].cells[t.y]; t.r[i].style.display='';
		while(v.hasChildNodes()){v=v.firstChild}
		t.a[i].v=v.nodeValue?v.nodeValue:''
	}
	for(i=0;i<t.w;i++){var c=t.h.cells[i]; if(c.className!='nosort'){c.className=this.p.headclass}}
	if(t.p==t.y&&!f){t.a.reverse(); x.className=t.d?this.p.ascclass:this.p.descclass; t.d=t.d?0:1}
	else{t.p=t.y; f&&this.p.sortdir==-1?t.a.sort(cp).reverse():t.a.sort(cp); t.d=0; x.className=this.p.ascclass}
	for(i=0;i<t.l;i++){var r=t.r[t.a[i].o].cloneNode(true); n.appendChild(r)}
	t.replaceChild(n,t.b); this.set(); this.alt(); if(this.p.paginate){this.size(z)} this.sethover()
};
//part to insert highlight script. prblem: where to?//
sorter.prototype.sethover=function(){
	if(this.p.hoverid){
		for(var i=0;i<this.t.l;i++){
			var r=this.t.r[i];
			r.setAttribute('onmouseover',this.n+'.hover('+i+',1)');
			r.setAttribute('onmouseout',this.n+'.hover('+i+',0)')	

		}
	}

};

sorter.prototype.calc=function(){
	if(this.p.sum||this.p.avg){
		var t=this.t, i=x=0, f,r;
		if(!T$$('tfoot',t)[0]){
			f=document.createElement('tfoot'); t.appendChild(f)
		}else{
			f=T$$('tfoot',t)[0]; while(f.hasChildNodes()){f.removeChild(f.firstChild)}
		}
		if(this.p.sum){
			r=this.newrow(f);
			for(i;i<t.w;i++){
				var j=r.cells[i];
				if(this.p.sum.exists(i)){
					var s=0, m=t.c[i].format||'';
					for(x=0;x<this.t.l;x++){
						if(t.a[x].s){s+=parseFloat(t.r[x].cells[i].innerHTML.replace(/(\$|\,)/g,''))}
					}
					s=decimals(s,t.c[i].decimals?t.c[i].decimals:2);
					s=isNaN(s)?'n/a':m=='$'?s=s.currency(t.c[i].decimals):s+m;
					r.cells[i].innerHTML=s
				}else{r.cells[i].innerHTML=' '}
			}
		}
		if(this.p.avg){
			r=this.newrow(f);
			for(i=0;i<t.w;i++){
				var j=r.cells[i];
				if(this.p.avg.exists(i)){
					var s=c=0, m=t.c[i].format||'';
					for(x=0;x<this.t.l;x++){
						if(t.a[x].s){s+=parseFloat(t.r[x].cells[i].innerHTML.replace(/(\$|\,)/g,'')); c++}
					}
					s=decimals(s/c,t.c[i].decimals?t.c[i].decimals:2);
					s=isNaN(s)?'n/a':m=='$'?s=s.currency(t.c[i].decimals):s+m;
					j.innerHTML=s
				}else{j.innerHTML=' '}
			}
		}
	}
};
sorter.prototype.newrow=function(p){
	var r=document.createElement('tr'), i=0; p.appendChild(r);
	for(i;i<this.t.w;i++){r.appendChild(document.createElement('td'))}
	return r
};
sorter.prototype.alt=function(){
	var t=this.t, i=x=0;
	for(i;i<t.l;i++){
		var r=t.r[i];
		if(t.a[i].s){
			r.className=x%2==0?this.p.evenclass:this.p.oddclass; var cells=T$$('td',r);
			for(var z=0;z<t.w;z++){cells[z].className=t.y==z?x%2==0?this.p.evenselclass:this.p.oddselclass:''}
			x++
		}
		if(!t.a[i].s){r.style.display='none'}
	}
};
sorter.prototype.page=function(s){
	var t=this.t, i=x=0, l=s+parseInt(this.p.size);
	if(this.p.totalrecid){T$(this.p.totalrecid).innerHTML=t.t}
	if(this.p.currentid){T$(this.p.currentid).innerHTML=this.g}
	if(this.p.startingrecid){
		var b=((this.g-1)*this.p.size)+1, m=b+(this.p.size-1); m=m<t.l?m:t.t; m=m<t.t?m:t.t;
		T$(this.p.startingrecid).innerHTML=t.t==0?0:b;; T$(this.p.endingrecid).innerHTML=m
	}
	for(i;i<t.l;i++){var r=t.r[i]; if(t.a[i].s){r.style.display=x>=s&&x<l?'':'none'; x++}else{r.style.display='none'}}
};
sorter.prototype.move=function(d,m){
	this.goto(d==1?(m?this.d:this.g+1):(m?1:this.g-1))
};
sorter.prototype.goto=function(s){
	if(s<=this.d&&s>0){this.g=s; this.page((s-1)*this.p.size)}
};
sorter.prototype.size=function(s){
	var t=this.t;
	if(s){this.p.size=s}
	this.g=1; this.d=Math.ceil(this.t.t/this.p.size);
	if(this.p.navid){T$(this.p.navid).style.display=this.d<2?'none':'block'}
	this.page(0);
	if(this.p.totalid){T$(this.p.totalid).innerHTML=t.t==0?1:this.d}
	if(this.p.pageddid){
		var d=T$(this.p.pageddid), l=this.d+1;
		d.setAttribute('onchange',this.n+'.goto(this.value)');
		while(d.hasChildNodes()){d.removeChild(d.firstChild)}
		for(var i=1;i<=this.d;i++){
			var o=document.createElement('option');
			o.value=i; o.innerHTML=i; d.appendChild(o)
		}
	}
};
sorter.prototype.showall=function(){
	this.size(this.t.t)
};
sorter.prototype.search=function(f){
	var i=x=n=0, k=-1, q=T$(f).value.toLowerCase();
	if(this.p.colddid){k=T$(this.p.colddid).value}
	var s=(k==-1)?0:k, e=(k==-1)?this.t.w:parseInt(s)+1;
	for(i;i<this.t.l;i++){
		var r=this.t.r[i], v;
		if(q==''){
			v=1
		}else{
			for(x=s;x<e;x++){
				var b=r.cells[x].innerHTML.toLowerCase();
				if(b.indexOf(q)==-1){v=0}else{v=1; break}
			}
		}
		if(v){n++}
		this.t.a[i].s=v
	}
	this.t.t=n;
	if(this.p.paginate){this.size()}
	this.calc(); this.alt()
};
sorter.prototype.hover=function(i,d){
	this.t.r[i].id=d?this.p.hoverid:''
};
sorter.prototype.set=function(){
	var t=T$(this.id); t.b=T$$('tbody',t)[0]; t.r=t.b.rows; this.t=t
};
Array.prototype.exists=function(v){
	for(var i=0;i<this.length;i++){if(this[i]==v){return 1}} return 0
};
Number.prototype.currency=function(c){
	var n=this, d=n.toFixed(c).split('.');
	d[0]=d[0].split('').reverse().join('').replace(/(\d{3})(?=\d)/g,'$1,').split('').reverse().join('');
	return '$'+d.join('.')
};
function decimals(n,d){return Math.round(n*Math.pow(10,d))/Math.pow(10,d)};
function cp(f,c){
	var g,h; f=g=f.v.toLowerCase(); c=h=c.v.toLowerCase();
	var i=parseFloat(f.replace(/(\$|\,)/g,'')), n=parseFloat(c.replace(/(\$|\,)/g,''));
	if(!isNaN(i)&&!isNaN(n)){g=i,h=n}
	i=Date.parse(f); n=Date.parse(c);
	if(!isNaN(i)&&!isNaN(n)){g=i; h=n}
	return g>h?1:(g<h?-1:0)
};
return{sorter:sorter}



}();

see the comment?i think that's the part where the table is highlighted on mouseover. i tried inserting your code there but then, the highlight on mouseover didn't work anymore..maybe you know what to do? :-\

 

Link to comment
Share on other sites

Hi Geek,

I think to give one Highlight to a Row when mouse is over is simple .... You can Study following code, and not make things complex it's not much

complex ....

 

<html>
<head>
<style type="text/css">
<!--
#mytable {
  border-collapse: collapse;
  width: 300px;
}
#mytable th,
#mytable td
{
  border: 1px solid #000;
  padding: 3px;
}
#mytable tr.highlight {
  background-color: #eee;
}
//-->
</style>
<script type="text/javascript" src="jquery-1.4.4.js"></script>
<script type="text/javascript">
// var oldHistLength = history.length;
// setInterval ( "checkHistory()", 100 );
  
$(
function()
{
  $("#mytable tr").hover(
   function()
   {
    $(this).addClass("highlight");
   },
   function()
   {
    $(this).removeClass("highlight");
   }
  )
}
);




</script>
</head>

<body >

<table id="mytable">
<tr>
  <th>Foo</th>
  <td>Lorem</td>
  <td>Ipsum</td>
</tr>
<tr>
  <th>Bar</th>
  <td>Dolor</td>
  <td>Sit</td>
</tr>
<tr>
  <th>Baz</th>
  <td>Amet</td>
  <td>Consectetuer</td>
</tr>
</table>
</body>

 

Don't Worry abt PHP , it has no hand in highlighting !!! .... be happy coding

 

Bye Anes  ;D

 

Link to comment
Share on other sites

hi there, sorry for the delay. been busy again with work. :)

thanks for the response logicslab. :)

but highlight on mouse over isn't exactly the problem..it's highlighting a row when it's clicked.

 

i've posted the javascript because i don't know what part of the script to modify,or where to put a highlight on click script there..here,let me show you the image of the table..

 

forfrreaks.jpg

 

as you can see, the first row's been highlighted on mouse over. and in the last column on the right, are image button i've placed for adding,deleting,etc..

 

now my goal is, when i click on one of these buttons, say the one with the "plus" sign on the last row, that row should automatically be highlighted and depending on which row i click. of course, the highlight on mouse over should still remain.. i hope that's clear.. :-\

 

[attachment deleted by admin]

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.